# 扁平化数组
var a = [1, [2, [3, 4, 5]]]
console.log(flatten(a));
1
2
2
# 1. 递归
function flatten(arr) {
let rst = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
rst = rst.concat(flatten(arr[i]))
} else {
rst.push(arr[i])
}
}
return rst;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 2. reduce
function flatten(arr) {
return arr.reduce((prev, next) => {
return prev.concat(Array.isArray(next) ? flatten(next) : next)
}, [])
}
1
2
3
4
5
2
3
4
5
# 3. some+扩展运算符
用数组的some方法取出仍是数组的项
利用扩展运算符拼接到原数组中
function flatten(arr) {
while (arr.some((item) => Array.isArray(item))) {
arr = [].concat(...arr)
}
return arr;
}
1
2
3
4
5
6
2
3
4
5
6
# 4. toString+split
arr.toString().split(',')
// 1,2,3,4,5 => ["1","2","3","4","5"]
1
2
2
# 5. ES6 flat
arr.flat(Infinity) // 参数为1时默认展开一层数组,Infinity时都要展开
1
# 6. JSON (stringify,parse)
数组转为字符串,去掉 [ , ]
再在外层补上[], 转为数组
function flatten(arr) {
let str = JSON.stringify(arr);
str = str.replace(/(\[|\])/g, '')
str = '[' + str + ']'
return JSON.parse(str)
}
1
2
3
4
5
6
2
3
4
5
6