Search This Blog

2024/04/19

Javascript Interview Question:Search keyword in Nexted Array

Problem Statement:
Given a nexted array of multiple levels find if a value exists in that
nexted array. E.g.For
const nextedArray = [0, 1, [2, [3, [4, 5]]]];
if we pass 5 to be found then it should return true.if we pass 7 it should
return false.
Solution:
function findInNextedArray(nextedArray, valueTobeFound) {
function flattenNextedArray(nextedArray) {
let output = [];
for (let i = 0; i < nextedArray.length; i++) {
if (Array.isArray(nextedArray[i])) {
let intermediateResult = flattenNextedArray(nextedArray[i]);
output = output.concat(intermediateResult);
} else {
output.push(nextedArray[i]);
}
}
return output;
}

let flattenedNextedArray = flattenNextedArray(nextedArray);
return flattenedNextedArray.includes(valueTobeFound);
}

//driver code
const nextedArray = [0, 1, [2, [3, [4, 5]]]];
const valueTobeFound = 5;
let foundInArray = findInNextedArray(nextedArray, valueTobeFound);
let response = foundInArray ? "found" : "not found";
console.log(`${valueTobeFound} is ${response} in given nexted array`);

Output:
5 is found in given nexted array

Note:
Their is inbuild flat method on array that also give you flatten array.
Using that method we can do same thing as follows.

const nextedArray = [0, 1, [2, [3, [4, 5]]]];
const valueTobeFound = 5;
let response = nextedArray.flat(Infinity).includes(valueTobeFound) ?
"found":"not found"
console.log(`${valueTobeFound} is ${response} in given nexted array`);

Output:
5 is found in given nexted array

No comments:

Post a Comment