preface

Arrays are the second most frequently used data structure in JS after objects, and there are a number of apis available to talk about how to flatten arrays.

Array flattening converts an array of nested layers (nesting can be any number of layers) into an array of only one layer

flat

The flat(depth) method concatenates all subarrays recursively to the specified depth and returns a new array. Depth specifies the depth of the structure in the nested array. The default value is 1

[1.2[3]].flat(1) / / [1, 2, 3]

[1.2[3[4]]].flat(2) // [1, 2, 3, 4]

[1.2[3[4[5]]]].flat(Infinity) // [1, 2, 3, 4, 5]
Copy the code

Flat () has compatibility problems and is not recommended

reduce

function flatten(arr) {
  return arr.reduce((a, b) = > {
    // return Array.isArray(b) ? a.concat(flatten(b)) : a.concat(b);
    return a.concat(Array.isArray(b) ? flatten(b) : b); } []); };// es6
const flatten = arr= >
  arr.reduce((a, b) = > a.concat(Array.isArray(b) ? flatten(b) : b), []);


flatten([1[2.3].4The [[5.6].7]])  // [1, 2, 3, 4, 5, 6, 7]
Copy the code

toString

The elements that apply only to arrays are numbers

function flatten(arr) {
  return arr.toString().split(",").map(item= > +item);
};


flatten([1[2.3].4The [[5.6].7]])  // [1, 2, 3, 4, 5, 6, 7]
Copy the code

[].concat(… arr)

function flatten(arr) {
  return !Array.isArray(arr) ? arr : [].concat.apply([], arr.map(flatten));
}


flatten([1[2.3].4The [[5.6].7]])  // [1, 2, 3, 4, 5, 6, 7]
Copy the code

generator

function* flatten(arr) {
  if (!Array.isArray(arr)) yield arr;
  else for (let el of arr) yield* flatten(el);
}

let flattened = [...flatten([1[2[3[4]]]]];// [1, 2, 3, 4]
Copy the code

String filtering

Converts the input array to a string and removes all parentheses ([]) and parses the output to an array

const flatten = arr= > JSON.parse(` [The ${JSON.stringify(arr).replace(/\[|]/g.' ')}] `);
Copy the code

Undercore or lodash library

Use the Undercore library or loDash’s _. Flatten function, refer to the API documentation for details

_.flatten([1, [2], [3, [[4]]]]);
=> [1, 2, 3, 4];
Copy the code

reference

There are many other ways to implement a flatten array, and you can refer to the literature

  1. javascript-flattening-an-array-of-arrays-of-objects

  2. merge-flatten-an-array-of-arrays-in-javascript