Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to flat an array in javascript recursively

const arrToFlat = [1, [2, [[3, 4], 5], 6]];

function flatArray(arr) {

  return arr.reduce((flat, toFlatten) => flat.concat(
      Array.isArray(toFlatten) ? flatArray(toFlatten) : toFlatten), []);
}


function flatArrayIter(arr) {
  const tempArr = [...arr];
  const flat = [];

  while (tempArr.length) {
    
    const next = tempArr.pop();
    
    Array.isArray(next) ? tempArr.push(...next) : flat.push(next);
  }
  
  return flat.reverse();
}
Source by lodash.com #
 
PREVIOUS NEXT
Tagged: #flat #array #javascript #recursively
ADD COMMENT
Topic
Name
8+5 =