// 原数组
var a = [1, 2, [3, 4, [5, [6]]]]
// 期望得到 => [1, 2, 3, 4, 5, 6]
方法一:reduce()
function flatten(a) {
return a.reduce((total, currentValue) => {
return total.concat(Array.isArray(currentValue)
? flatten(currentValue)
: currentValue)},
[]
)
}
// => [1, 2, 3, 4, 5, 6]
方法二:lodash 的 flattenDeep()
import '_' from 'lodash'
_.flattenDeep(a)
// => [1, 2, 3, 4, 5, 6]
方法三:手写一个flat方法
function flat(arr) {
// 判断数组中是否有深层数组
const isDeep = arr.some(item => item instanceof Array)
// 无深层数组,返回当前数组
if (!isDeep) {
return arr
}
// 有深层数组,继续拍平
const res = Array.prototype.concat.apply([], arr)
flat(res)
}
flat(a)
// => [1, 2, 3, 4, 5, 6]
三种方法都是得到一个新的数组,不改变原数组