
Flatten Deeply Nested Array
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 stac
Continue reading on Dev.to JavaScript
Opens in a new tab


