数组扁平化
# 数组扁平化
const arr = [1, [2, [3, [4, 5]]], 6];
// 第一种 自带flat方法
console.log(arr.flat(Infinity), '第一种');
// 第二种方法 for 循环
function flatten(arr, res) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
flatten(arr[i], res);
} else {
res.push(arr[i]);
}
}
return res;
}
// 第三种 reduce
function flatten2(arr) {
return arr.reduce(
(pre, cur) => pre.concat(cur instanceof Array ? flatten2(cur) : cur),
[]
);
}
// 第四种 使用stack
function flatten4(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const first = stack.shift();
if (Array.isArray(first)) {
stack.unshift(...first);
} else {
result.push(first);
}
}
return result;
}
// 如果数组的项全为数字,可以使用join(),toString()进行扁平化操作。
console.log(
arr.toString().split(',').map((item) => +item)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44