1. A two-dimensional array, you can simply use the flat () method let arr = [[1, 2], [3, 4], [5, 6]]. Flat ();

Let arr = [[1, 2], [3, 4], [5, 6]]. Flat (); console.log(arr); / / [6]Copy the code

If it’s a multi-dimensional array, flat() won’t work,Var newArray = arr.flat([depth]),

Parameter: depth, optional, specifies the depth of the structure to extract the nested array. The default value is 1.

Let arr = [[1, 2], [3, 4], [5, 6]]. Flat (Infinity); console.log(arr); / / [6]Copy the code

2. Iterative implementation (ES6 extension operator…)

Const arr = [1, 2, three, four, five, [6, 7], 8], 9, 10, [11, [12, 13]]]. const flatten = (arr) => { while(arr.some(item=>Array.isArray(item))){ arr=[].concat(... arr); } return arr; } console.log(flatten(arr)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]Copy the code

3. Ordinary recursive implementation

Const arr = [1, 2, three, four, five, [6, 7], 8], 9, 10, [11, [12, 13]]]. const flatten = (arr) => { let result = []; arr.forEach((item, i, arr) => { if (Array.isArray(item)) { result = result.concat(flatten(item)); } else { result.push(arr[i]) } }) return result; }; console.log(flatten(arr));Copy the code

4. Advanced recursion (Reduce method)

const flatten = (array) => array.reduce((acc,cur)=> (Array.isArray(cur)? [...acc,...flatten(cur)]:[...acc,cur]),[])Copy the code

​​​​

5. toString()

This method takes advantage oftoStringTurn the array into a comma-separated string, and then change each item back to its original type by iterating through the array.​​ ​

Const arr = [1, 2, three, four, five, [6, 7], 8], 9, 10, [11, [12, 13]]]. const flatten = (arr) => arr.toString().split(',').map((item) => +item); console.log(flatten(arr));Copy the code

​6.[].concat.apply

Const arr = [1, 2, three, four, five, [6, 7], 8], 9, 10, [11, [12, 13]]]. const flatten = (arr) => { while (arr.some(item => Array.isArray(item))){ arr = [].concat.apply([], arr); } return arr; } console.log(flatten(arr));Copy the code