如何压平在JavaScript嵌套数组? [英] How to flatten nested array in javascript?

查看:445
本文介绍了如何压平在JavaScript嵌套数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我们所知,扁平化数组 [0,1],[2,3],[4,5]] 使用方法减少()

As we know, to flatten the array [[0, 1], [2, 3], [4, 5]] by using the method 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]

推荐答案

这是递归(替代 看到的jsfiddle这里 ),并应接受深度避免堆栈溢出的任何级别。

This is an alternative to recursion (see jsfiddle here) and should accept any level of depth which avoids stack overflow.

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;
}

这篇关于如何压平在JavaScript嵌套数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆