数组扁平化
# 几种方法如下
- toString + split
- join + split
- Array.prototype.flat(Infinity)
- reduce + concat + isArray 递归实现
- Use a stack 堆栈非递归
- Use Generator function 生成器
# toString + split
function flatDeep(array: any[]): number[] {
return array
.toString()
.split(',')
.map((item) => Number(item))
}
1
2
3
4
5
6
2
3
4
5
6
# join + split
function flatDeep(array: any[]): number[] {
return array
.join()
.split(',')
.map((item) => Number(item))
}
1
2
3
4
5
6
2
3
4
5
6
# Array.prototype.flat(Infinity)
function flatDeep(array): number[] {
return array.flat(Infinity)
}
1
2
3
2
3
# reduce + concat + isArray 递归实现
function flatDeep(array: any[], depth = 1): number[] {
return depth > 0
? array.reduce((pre, cur, index, arr) => {
return pre.concat(Array.isArray(cur) ? flatDeep(cur, depth - 1) : cur)
}, [])
: array.slice()
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# Use a stack 堆栈非递归
// non recursive flatten deep using a stack
// note that depth control is hard/inefficient as we will need to tag EACH value with its own depth
// also possible w/o reversing on shift/unshift, but array OPs on the end tends to be faster
function flatten(input) {
const stack = [...input]
const res = []
while (stack.length) {
// pop value from stack
const next = stack.pop()
if (Array.isArray(next)) {
// push back array items, won't modify the original input
stack.push(...next)
} else {
res.push(next)
}
}
// reverse to restore input order
return res.reverse()
}
const arr = [1, 2, [3, 4, [5, 6]]]
flatten(arr)
// [1, 2, 3, 4, 5, 6]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Use Generator function 生成器
function* flatten(array, depth) {
if (depth === undefined) {
depth = 1
}
for (const item of array) {
if (Array.isArray(item) && depth > 0) {
yield* flatten(item, depth - 1)
} else {
yield item
}
}
}
const arr = [1, 2, [3, 4, [5, 6]]]
const flattened = [...flatten(arr, Infinity)]
// [1, 2, 3, 4, 5, 6]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 总结
数组扁平化的方法有:
- toString + split
- join + split
- Array.prototype.flat(Infinity)
- reduce + concat + isArray 递归实现
- Use a stack
- Use Generator function 生成器
编辑 (opens new window)
上次更新: 2021/08/20 17:31:16