数组扁平化方法

  //方法一:循环递归
    var complexdatalist = [1, [2, 3], [4, 5], [6, [7, 8]], [9, [10, [11, 12]]]]
    function myconcat(complexdatalist) {
        var simpledatalist = [];
        for (var i = 0; i < complexdatalist.length; i++) {
            if (Array.isArray(complexdatalist[i])) {
                simpledatalist = simpledatalist.concat(myconcat(complexdatalist[i]));
            } else {
                simpledatalist = simpledatalist.concat(complexdatalist[i]);
            }
        }
        return simpledatalist
    }

    console.log(myconcat(complexdatalist));

    //方法2:reduce累加器
    var complexdatalist = [1, [2, 3], [4, 5], [6, [7, 8]], [9, [10, [11, 12]]]]
    function flatten(arr) {
        return arr.reduce(function (prev, item) {
            return prev.concat(Array.isArray(item) ? flatten(item) : item);
        }, []);
    }
    console.log(flatten(complexdatalist));

 

posted @ 2018-07-23 11:50  寂寞之砂  阅读(141)  评论(0编辑  收藏  举报