// 测试demo
const arr = [1, 3, 4, [5, 6], [7, 8, [9, 10]]]
console.log(flat(arr)); // [1, 3, 4, 5, 6, 7, 8, 9, 10];
// 手写flatten
function flatten(arr){
return arr.reduce((acc, curr) => {
const newValue = Array.isArray(curr) ? flatten(curr) : curr;
return acc.concat(newValue);
}, [])
}
// [1, 3, 4, [5, 6], [7, 8, [9, 10]]].toString() =》 '1,3,4,5,6,7,8,9,10'
//数组扁平化 技巧版
const flatten = arr => arr.toString().split(',').map(item => +item);
//数组扁平化 指定深度
const flatten = (arr, depth = 1) => {
return arr.reduce((curr, next) => {
return Array.isArray(next) && depth > 1 ? [...curr, ...flatten(next, depth - 1)] : [...curr, next]
}, []);
}
手写flatten
于 2023-05-07 20:57:49 首次发布