JavaScript数组深度扁平化处理

要求:把数组arr=[12,34,[122,324],[222,[333]];扁平化

思路:创建一个新数组,循环原数组判断每一项是否是数组是的话先递归,在调用const或push方法,不是直接const或push。

方法一:使用数组的concat方法(concat可以传入数组或值,合并到一个新的数组中。)

复制代码
const arr = [12,34,[122,324],[222,[333]]];

function flatten(arr) {
    let res = [];
    arr.forEach(el => {
        if (el instanceof Array) {
            let newArr = flatten(el);
            res = res.concat(newArr)
        } else {
            res = res.concat(el);
        }
    })
    return res
}
let newArr = flatten(arr);
console.log(newArr); // [ 12, 34, 122, 324, 222, 333 ]
复制代码

方法二:使用数组的push方法,数组递归之后再循环往新数组添加

复制代码
const arr = [12,34,[122,324],[222,[333]]];

function flatten(arr) {
    let res = [];
    arr.forEach(el => {
        if (el instanceof Array) {
            let newArr = flatten(el);
            newArr.forEach(item => res.push(item))
        } else {
            res.push(el);
        }
    })
    return res
}
let newArr = flatten(arr);
console.log(newArr); // [ 12, 34, 122, 324, 222, 333 ]
复制代码

 

posted @   雪旭  阅读(68)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示