javascript 有没有一种简单的方法可以使嵌套数组变平?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6032878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:13:07  来源:igfitidea点击:

Is there an easy way to make nested array flat?

javascriptarrays

提问by rsk82

That is to make this:

那就是要做到这一点:

[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]

[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]

into:

进入:

['dog','cat','chicken','bear','mouse','horse']

['dog','cat','chicken','bear','mouse','horse']

回答by ChewOnThis_Trident

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

It's note worthy that reduce isn't supported in IE 8 and lower.

值得注意的是,IE 8 及更低版本不支持 reduce。

developer.mozilla.org reference

developer.mozilla.org 参考

回答by elclanrs

In modern browsers you can do this without any external libraries in a few lines:

在现代浏览器中,你可以在没有任何外部库的情况下通过几行来做到这一点:

Array.prototype.flatten = function() {
  return this.reduce(function(prev, cur) {
    var more = [].concat(cur).some(Array.isArray);
    return prev.concat(more ? cur.flatten() : cur);
  },[]);
};

console.log([['dog','cat',['chicken', 'bear']],['mouse','horse']].flatten());
//^ ["dog", "cat", "chicken", "bear", "mouse", "horse"]

回答by Craig M

Grab underscore.jsand use the flattenfunction.

获取underscore.js并使用flatten函数。

_.flatten([ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]);

回答by vipin goyal

What about this one liner code ?

这一个班轮代码怎么样?

console.log([['dog', 'cat', ['chicken', 'bear']], [['mouse', 'horse'], 'lion']].join().split(','));

basically join will make comma separated string from nested array and using split you can get 1d array, nice ? bonusit'll work on all major browsers as well :)

基本上 join 会从嵌套数组中生成逗号分隔的字符串,使用 split 你可以获得一维数组,好吗?奖金它也适用于所有主要浏览器:)

回答by Andrzej Sawoniewicz

Small fix for ChewOnThis_Trident solution and it works perfect:

ChewOnThis_Trident 解决方案的小修复,它完美运行:

Array.prototype.flatten = function() {
    return this.reduce(function(a, b) {
        return a.concat(b);
    }, []);
};

回答by Alnitak

Assuming an array that's already unpacked from JSON, try this:

假设一个已经从 JSON 解包的数组,试试这个:

Array.prototype.flatten = function() {
    var r = [];
    for (var i = 0; i < this.length; ++i) {
        var v = this[i];
        if (v instanceof Array) {
            Array.prototype.push.apply(this, v.flatten());
        } else {
            r.push(v);
        }
    }
    return r;
};

It appears to work correctly on your input - see http://jsfiddle.net/alnitak/Ws7L5/

它似乎在您的输入上正常工作 - 请参阅http://jsfiddle.net/alnitak/Ws7L5/

回答by Code Maniac

Now in 2019you can easily use Array.flatwith whatever depth you want.

现在在 2019 年,您可以轻松地使用Array.flat任何您想要的深度。

let arr  = [ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]

let op = arr.flat(Infinity)

console.log(op)

Now if you want to get unique values you can combine both Set and flat

现在如果你想获得唯一的值,你可以结合 Set 和 flat

let arr  = [ ['dog','cat', ['chicken', 'bear', 'cat'] ],['mouse','horse', 'dog'], [[[['deeper','chicken']]]] ]

let unique  = [...new Set(arr.flat(Infinity))]

console.log(unique)
Browser comparability浏览器可比性除了 IE 之外,所有其他似乎都支持 IE 的您可以使用 polyfill。

回答by maheshmnj

The easiest way of flattening the Objects of any depth would be using the flat method

展平任何深度的对象的最简单方法是使用 flat 方法

var arr = [['dog','cat', ['chicken', 'bear']],[['mouse','horse'],'lion'] ]; 
var flattened = arr.flat(Infinity);
//output--> ["dog", "cat", "chicken", "bear", "mouse", "horse", "lion"]

More aout Flat()

更多关于 Flat()

回答by TrojanMorse

I know this is late but I also ran into a situation where I needed to make a multidimensional array into 1 array and I made a function as follows.

我知道这已经晚了,但我也遇到了一种情况,我需要将一个多维数组变成 1 个数组,然后我创建了一个函数,如下所示。

function nested(arr) {
    var noNest = arr.toString().split(',').filter(Boolean),
        i = 0;

    for(i;i<noNest.length; i++){
        if(isNaN(noNest[i])){
            return console.log(noNest);
        } else {
            noNest[i] = parseInt(noNest[i]);
        }
    }
    return console.log(noNest);
}

nested([[['a']], [['b']]]);

This also take the nested arrays inside the tested array and makes sure its one array as the final out put

这也采用测试数组中的嵌套数组,并确保其一个数组作为最终输出

回答by Yup.

This solution has been working great for me, and i find it particularly easy to follow:

这个解决方案对我很有用,我发现它特别容易遵循:

function flattenArray(arr) {
  // the new flattened array
  var newArr = [];

  // recursive function
  function flatten(arr, newArr) {
    // go through array
    for (var i = 0; i < arr.length; i++) {
      // if element i of the current array is a non-array value push it
      if (Array.isArray(arr[i]) === false) {
        newArr.push(arr[i]);
      }
      // else the element is an array, so unwrap it
      else {
        flatten(arr[i], newArr);
      }
    }
  }

  flatten(arr, newArr);

  return newArr;
}