数组扁平化的意思就是将多维数组降维
1 2 3 4 5 6 7 8
| const array = [1, 2, [3, 4, [5, 6], 7], 8, 9]
newArray1 = [1, 2, 3, 4, [5, 6], 7, 8, 9]
newArray2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
原生 flat 方法(ES2019)
flat() 方法扁平数组的同时,还能移除数组中的空位(Empty Slots)
1 2
| const array = [1, 2, [3, 4, [5, 6], 7], 8, 9]; console.log(array.flat());
|
flat 仿写
1 2 3 4 5 6 7 8 9 10 11 12 13
| function MyFlat(arr = [], depth = 1) { let result = []; arr.forEach(item => { if (Array.isArray(item) && depth ) { result.push(...MyFlat(item, depth - 1)); } else { result.push(item); } }) return result; } const array = [1, 2, [3, 4, [5, 6], 7], 8, 9]; console.log(MyFlat(array));
|
递归实现 (全量)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function fn(arr) { let result = []; arr.forEach(item => { if (item instanceof Array) { result = result.concat(fn(item)); } else { result.push(item); } }); return result; }
const array = [1, 2, [3, 4, [5, 6], 7], 8, 9]; console.log(fn(array));
|
reduce 实现 (全量)
1 2 3 4 5 6 7 8
| function fn(arr) { return arr.reduce((prev, cur) => { return prev.concat(Array.isArray(cur) ? fn(cur) : cur); }, []); }
const array = [1, 2, [3, 4, [5, 6], 7], 8, 9]; console.log(fn(array));
|
拍平一层的方式
ES6 解构:
1 2 3
| const array = [1, 2, [3, 4, [5, 6], 7], 8, 9]; const flattened = [].concat(...array); console.log(flattened);
|
ES6 之前:
1 2 3
| const array = [1, 2, [3, 4, [5, 6], 7], 8, 9]; const flattened = [].concat.apply([], array); console.log(flattened);
|