将二维 JavaScript 数组转换为一维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14824283/
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
Convert a 2D JavaScript array to a 1D array
提问by Anderson Green
I want to convert a 2D JavaScript array to a 1D array, so that each element of the 2D array will be concatenated into a single 1D array.
我想将二维 JavaScript 数组转换为一维数组,以便将二维数组的每个元素连接成一个一维数组。
Here, I'm trying to convert arrToConvertto a 1D array.
在这里,我试图转换arrToConvert为一维数组。
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
console.log(get1DArray(arrToConvert)); //print the converted array
function get1DArray(2dArr){
//concatenate each element of the input into a 1D array, and return the output
//what would be the best way to implement this function?
}
回答by Bla? Zupan?i?
Use the ES6 Spread Operator
使用 ES6 扩展运算符
arr1d = [].concat(...arr2d);
Note that this method is only works if arr2dhas less than about 100 000 subarrays. If your array gets larger than that you will get a RangeError: too many function arguments.
请注意,此方法仅适用arr2d于少于大约 100 000 个子阵列的情况。如果您的数组变得更大,您将获得一个RangeError: too many function arguments.
For > ~100 000 rows
对于 > ~100 000 行
arr = [];
for (row of table) for (e of row) arr.push(e);
concat()is too slow in this case anyway.
concat()无论如何在这种情况下太慢了。
The Underscore.js way
Underscore.js 方式
This will recursively flatten arrays of any depth (should also work for large arrays):
这将递归地展平任何深度的数组(也应该适用于大型数组):
arr1d = _.flatten(arr2d);
If you only want to flatten it a single level, pass trueas the 2nd argument.
如果您只想将其展平一个级别,请将其true作为第二个参数传递。
A short < ES6 way
一个简短的 < ES6 方式
arr1d = [].concat.apply([], arr2d);
回答by Marty
回答by marteljn
How about:
怎么样:
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
function get1DArray(arr){
return arr.join().split(",");
}
console.log(get1DArray(arrToConvert));
回答by blvz
Try .reduce()
尝试 .reduce()
var test2d = [
["foo", "bar"],
["baz", "biz"]
];
var merged = test2d.reduce(function(prev, next) {
return prev.concat(next);
});
回答by Balasubramanian
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
var modifiedArray = arrToConvert.map(function(array){
return array[0]+array[1]+array[2];
});
Another Example
另一个例子
var passengers = [
["Thomas", "Meeks"],
["Gregg", "Pollack"],
["Christine", "Wong"],
["Dan", "McGaw"]
];
var modifiedNames = passengers.map(function(convArray){
return convArray[0]+" "+convArray[1];
});
回答by Saturnix
var arrToConvert = [[0, 0, 1], [2, 3, 3], [4, 4, 5]];
function get1DArray(arr){
var result = new Array();
for (var x = 0; x < arr.length; x++){
for (var y = 0; y < arr[x].length; y++){
result.push(arr[x][y])
}
}
return result
}
alert (get1DArray(arrToConvert))

