function flatten(arr = [], depth = 1) {
let 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;
}
// concat() 方法不会更改现有数组,而是返回一个新数组,其中包含已连接数组的值。
function flatten2(arr = [], depth = 1) {
if(depth <= 0){
return arr;
}
return arr.reduce((curr, item) => curr.concat(Array.isArray(item) ? flatten2(item, depth - 1) : item), []);
}
function flatten3(arr = [], depth = 1) {
let result = [];
(function flat(arr, depth) {
for (let item of arr) {
if (Array.isArray(item) && depth > 0) {
flat(item, depth - 1);
} else {
// 使用concat 不用 push 可以除去非空元素
// 除空元素,添加非 undefined 元素
// concat() 方法不会更改现有数组,而是返回一个新数组,其中包含已连接数组的值。
result.push(item);
}
}
})(arr, depth);
return result;
}
const arr = [1, 2, 3, [], [4, 5, [], [4]]];
const result = flatten2(arr, 2);
console.log(result);
前端手撕代码——手撕flat
于 2023-06-16 18:01:46 首次发布