我想将 2D JavaScript 数组转换为 1D 数组,以便 2D 数组的每个元素都将连接成一个 1D 数组。
在这里,我正在尝试转换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?
}
使用 ES6 扩展运算符
arr1d = [].concat(...arr2d);
请注意,此方法仅在以下情况下才有效arr2d
具有少于大约 100 000 个子阵列。如果你的数组变得比这个大,你会得到一个RangeError: too many function arguments
.
对于 > ~100 000 行
arr = [];
for (row of table) for (e of row) arr.push(e);
concat()
无论如何,在这种情况下太慢了。
Underscore.js 方式
这将递归地展平任何深度的数组(也应该适用于大型数组):
arr1d = _.flatten(arr2d);
如果您只想将其展平为一个级别,请通过true
作为第二个参数。
一个简短的
arr1d = [].concat.apply([], arr2d);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)