小编典典

如何在JavaScript中展平嵌套数组?

javascript

如我们所知,[[0, 1], [2, 3], [4, 5]]通过使用方法将数组展平reduce()

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
});

那么如何将此数组展平[[[0], [1]], [[2], [3]], [[4], [5]]][0, 1, 2, 3, 4, 5]


阅读 365

收藏
2020-05-01

共1个答案

小编典典

这是递归的一种替代方法,并且应接受任何深度级别,以避免堆栈溢出。

var array = [[0, 1], [2, 3], [4, 5, [6, 7, [8, [9, 10]]]]];

console.log(flatten(array), array); // does not mutate array

console.log(flatten(array, true), array); // array is now empty



// This is done in a linear time O(n) without recursion

// memory complexity is O(1) or O(n) if mutable param is set to false

function flatten(array, mutable) {

    var toString = Object.prototype.toString;

    var arrayTypeStr = '[object Array]';



    var result = [];

    var nodes = (mutable && array) || array.slice();

    var node;



    if (!array.length) {

        return result;

    }



    node = nodes.pop();



    do {

        if (toString.call(node) === arrayTypeStr) {

            nodes.push.apply(nodes, node);

        } else {

            result.push(node);

        }

    } while (nodes.length && (node = nodes.pop()) !== undefined);



    result.reverse(); // we reverse result to restore the original order

    return result;

}
2020-05-01