let arrItem=[1,[2,3,[4,5],[5,[3,[29]]]]];
I was asked in the interview to flatten this array meaning convert this array into something like this [1,2,3,4,5,5,3,29];
So, my first approach was to use a inbuild flat method of array.
arrItem.flat()
Now, the problem with this is it doen't flat deeply nested array. So you have to provide the depth. Here we can provide depth as infinity. So the answer would be.
arrItem.flat(Infinity)
Now, the interviewer will ask for a custom implementation of flat method.
There are two approach to do so.
1) Recursive Approach
Array.prototype.flattenArray=function(){
// This is recursion Approach
let array=this;
let output=[];
function flatArray(array){
for(let item of array){
if(Array.isArray(item)){
flatArray(item)
}
else {
output.push(item)
}
}
}
flatArray(array)
return output;
}
2) Using Stack
let arrItem=[1,[2,3,[4,5],[5,[3,[29]]]]];
Array.prototype.flattenArray = function(depth=1){
let stack=[];
let output=[];
for(let i=this.length-1;i>=0;i--){
stack.push([this[i],depth])
}
while(stack.length){
let [item,depth]=stack.pop();
if(Array.isArray(item) && depth>0){
for(let i=item.length-1;i>=0;i--){
stack.push([item[i],depth-1]);
}
}
else {
output.push(item);
}
}
return output
}
console.log(arrItem.flattenArray(2)); // Provide any depth here for nesting. Infinity,for deeply nested.
Top comments (0)