Array flattening method

In the operation of arrays, we often encounter the situation of nested arrays, and we often need a single-layer array.

That is [1,2,[3,4,[5,[6,[7]]]]] ==="[ 1, 2, 3, 4, 5, 6, 7 ] , we call it an array flattening.

method one

If it is an array of pure numbers (you can also try a string), you can use the simple toString and split methods

var arr = [1,'a',[3,'4',['b',[6,[7]]]]]
console.log(arr.toString().split(','))
//[ '1', 'a', '3', '4', 'b', '6', '7' ]

Method Two

Use recursive method, keep calling if the element is still an array

var arr = [1,'a',[3,'4',['b',[6,[7]]]]];

function flatten(arr) {
  let res = [];
  for (let i=0,len=arr.length;i<len;i++) {
    if(Array.isArray(arr[i])) {
      res = res.concat(flatten(arr[i]));
    }else{
      res.push(arr[i])
    }
  }
  return res;
}
console.log(flatten(arr))
//[ 1, 'a', 3, '4', 'b', 6, 7 ]

The above code can be simplified by the reduce method of array

var arr = [[1,[2]],'a',[3,'4',['b',[6,[7]]]]]

function flatten(arr) {
  return arr.reduce((prev,item) => {
    return prev.concat(Array.isArray(item)?flatten(item):item);
  }, []);
}
console.log(flatten(arr))
//[ 1, 2, 'a', 3, '4', 'b', 6, 7 ]

Both the reduce and reduceRight methods iterate over all items in the array and build a final return value. The first method traverses forward, and the second traverses backward.

Both accept two arguments, the first is the function to execute for each item, and the second is an optional argument to use as an initial value for the base of the merge. The function takes 4 parameters: the previous value, the current value, the index of the item, the array object.

Re-simplification

var arr = [[1,[2]],'a',[3,'4',['b',[6,[7]]]]];
const Flat6 = arr => arr.reduce((a, b) => a.concat(Array.isArray(b) ? Flat6(b) : b), []); 
console.log(Flat6(arr))
//[ 1, 2, 'a', 3, '4', 'b', 6, 7 ]

 

Method three

If it is determined to be a simple double-nested array, you can use the spread operator provided by es6

var arr = [[1,2], [3], [4,5,6 ]]
console.log([].concat(...arr))
//[ 1, 2, 3, 4, 5, 6 ]

If you find a better way, please add it~~

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324980137&siteId=291194637
Recommended