数组扁平化常见的方法

数组扁平化的意思就是将多维数组降维

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()); // [ 1, 2, 3, 4, [ 5, 6 ], 7, 8, 9 ]

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 ]

递归实现 (全量)

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)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

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)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

拍平一层的方式

ES6 解构:

1
2
3
const array = [1, 2, [3, 4, [5, 6], 7], 8, 9];
const flattened = [].concat(...array);
console.log(flattened); // [ 1, 2, 3, 4, [ 5, 6 ], 7, 8, 9 ]

ES6 之前:

1
2
3
const array = [1, 2, [3, 4, [5, 6], 7], 8, 9];
const flattened = [].concat.apply([], array);
console.log(flattened); // [ 1, 2, 3, 4, [ 5, 6 ], 7, 8, 9 ]