手写js 数组打平

复制代码
console.log("array flat");
// 1. 因为只有数组才有 concat 方法,所以这里必须写入初始值  空数组  只能打平一层
// const flat = (list) => list.reduce((a, b) => a.concat(b), []);
// 2. 直接用 concat 和扩展运算符,只能打平一层
// const flat = (list) => [].concat(...list);
// 3. 加一个递归,可以打平深层数组
// const flat = (list) =>
//     list.reduce((a, b) => a.concat(Array.isArray(b) ? flat(b) : b), []);
// 4. 支持传入打平的深度
const flat = (list, depth) => {
    if (depth === 1) {
        return list;
    }
    return list.reduce((a, b) => {
        return a.concat(Array.isArray(b) ? flat(b, depth - 1) : b);
    }, []);
};
// 测试用例
console.log(flat([1, 2, 3, [4, 5, [6, 7, [0, 9, 0], 8], 6], 8], 5));
复制代码

 

posted @   蓓蕾心晴  阅读(108)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示