Skip to content

Commit

Permalink
created flatten Function
Browse files Browse the repository at this point in the history
  • Loading branch information
Lovegupta112 committed Aug 29, 2023
1 parent 97c9280 commit 0ff6283
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
41 changes: 41 additions & 0 deletions flatten.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Flattens a nested array (the nesting can be to any depth).
// Hint: You can solve this using recursion.
// Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4];



function flatten(elements,level) {


let flattenArr=[];
let depth=level;

if(level===true){
depth=1;
}

/*approach:-
we will iterate over array and will check if any element of array is array or not
if we get any element that is array so we will again call flatten function and pass that element
when it will return array as result so we will store into flatternArr using spread operator
*/

for(let index=0;index<elements.length;index++){

//for checking if any element is array or not , we will use isArray method

if(Array.isArray(elements[index]) && depth>0){
// console.log('Arr: ',elements[index]);
flattenArr.push(...flatten(elements[index],depth-1));
}
else{
// console.log('element:',elements[index]);
flattenArr.push(elements[index]);
}
}
return flattenArr;
}


module.exports=flatten;

11 changes: 11 additions & 0 deletions test/testFlatten.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const flattenFunc=require('../flatten');

let arr=[1,2,[4,[5,6,[8,9,10]]],5,[6,7]];

let flattenArr=flattenFunc(arr,true);

console.log('Flatten Array of depth-1: ',flattenArr);

flattenArr=flattenFunc(arr,2);

console.log('Flatten Array of depth-2: ',flattenArr);

0 comments on commit 0ff6283

Please sign in to comment.