-
Notifications
You must be signed in to change notification settings - Fork 18
Open
Labels
Description
所谓数组扁平化,就是将内嵌数组转换成一层数组,这里有四种方式
// 递归
function flatten1 (arr) {
let res = []
arr.forEach((item) => {
if (Array.isArray(item)) {
res = res.concat(flatten1(item))
} else {
res.push(item)
}
})
return res
}
// 当所有数组项都为数字的时候,可以使用toString()方法,
function flatten2 (arr) {
return arr.toString().split(',').map((item) => {
return +item
})
}
// ...扩展运算符
function flatten3 (arr) {
while (arr.some((item) => Array.isArray(item))) {
arr = [].concat(...arr)
}
return arr
}
// reduce方法
function flatten4 (arr) {
return arr.reduce((prev, next) => {
return prev.concat(Array.isArray(next) ? flatten4(next) : next)
}, [])
}
let arr = [1, 2, [3, [4, 5]]] // [1,2,3,4,5]