概念
将多维数组变成一维数组的过程
[1, [2, 3, [4, 5]]] ------> [1, 2, 3, 4, 5]
实现方式
1. ES6的Generator 函数
无视数据类型
function *flatten(arr) {
for (const item of arr) {
if (Array.isArray(item)) {
yield *flatten(item)
} else {
yield item
}
}
}
const newArr = [...flatten([1, true, {isNewHero: true, name: '阿古朵'}, [2, {name: ['韩信', '赵云']}, [3]]])]
console.log(newArr)
2. join+split
只对数字类型的数组有效
[1, 2, 3, [4, 5, [6]]].join(',').split(',').map(item => parseInt(item))
3. toString+split
只对数字类型的数组有效,和第二种方式大同小异
[1, 2, 3, [4, 5, [6]]].toString().split(',').map(item => parseInt(item))
4. reduce+concat
无视数据类型
function flatten(arr) {
return arr.reduce((result, item)=> {
return result.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
const newArr = [...flatten([1, 2, 3, [4, 5, [6]]])]
console.log(newArr) // [1, 2, 3, 4, 5, 6]
5. 数组falt()方法
可指定深度,默认深度为1,传Infinity表示彻底扁平化
无视数据类型,推荐指数5颗星
[1, 2, 3, [4, 5, [6]]].flat(Infinity)
6. forEach+isArray+push
深度可控,无视数组类型
const eachFlat = (arr = [], depth = 1) => {
const result = []; // 缓存递归结果
// 开始递归
(function flat(arr, depth) {
// forEach 会自动去除数组空位
arr.forEach((item) => {
// 控制递归深度
if (Array.isArray(item) && depth > 0) {
// 递归数组
flat(item, depth - 1)
} else {
// 缓存元素
result.push(item)
}
})
})(arr, depth)
// 返回递归结果
return result;
}
console.log(eachFlat([{id:'123'}, true, 3, [4, 5, [6]]], Infinity))