美文网首页
js递归(二)——合并多维数组

js递归(二)——合并多维数组

作者: 储锋 | 来源:发表于2018-12-21 16:57 被阅读0次

    1.递归实现

     let [a,b,c] = [
            [1,2,3,[3,4,5,[5,6,7]]],
            ["a","b",["c","d",["aa","bb"]]],
            ["aaaa","bbbb"]
          ],
        //递归实现单个数组的多维转一维
         arrCat = a => a.reduce((p,c)=> p.concat(Array.isArray(c)?arrCat(c):c),[]),
        //es6扩展运算符
         arr= [...arrCat(a),...arrCat(b),...arrCat(c)]
        console.log(arr);
    //[1, 2, 3, 3, 4, 5, 5, 6, 7, "a", "b", "c", "d", "aa", "bb", "aaaa", "bbbb"]
    

    用forEach和reduce做一个简单的封装joinArr()函数显示数组的合并

    let joinArr = (...arr)=> {
            let newArr = [];
            // [...arr].forEach(item=>{
            //     newArr.push(...arrCat(item))
            // })
            // return newArr
            return [...arr].reduce((p,c)=>{
                return p.concat(arrCat(c))
            },[])   
        }
    console.log(joinArr(a, b, c));
    //[1, 2, 3, 3, 4, 5, 5, 6, 7, "a", "b", "c", "d", "aa", "bb", "aaaa", "bbbb"]
    
    

    2.补充

    let [a,b,c] = [
            [1,2,3,[3,4,5,[5,6,7]]],
            ["a","b",["c","d",["aa","bb"]]],
            ["aaaa","bbbb"]
          ],
         k=[...a,...b,...c].toString().split(",");
        //字符串数字转成数字
         k=k.map(item=>{
            if (!isNaN(item-0)) return item-0
            return item
        })
        console.log(k);
    //[1, 2, 3, 3, 4, 5, 5, 6, 7, "a", "b", "c", "d", "aa", "bb", "aaaa", "bbbb"]
    

    完善:封装成joinArr()函数

     let [a,b,c] = [
                [1,2,3,[3,4,5,[5,6,7]]],
                ["a","b",["c","d",["aa","bb"]]],
                ["aaaa","bbbb"]
            ],
            joinArr = (...k) =>{
                    let newArr =[...k].toString().split(",").map(item=>{
                        if (!isNaN(item-0)) return item-0
                        return item
                    })
                return newArr
            }
        console.log(joinArr(a, b, c));
    

    相关文章

      网友评论

          本文标题:js递归(二)——合并多维数组

          本文链接:https://www.haomeiwen.com/subject/oywmkqtx.html