在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
如果你正在通过map/filter/sort等管道输出结果,并且你想连接数组的数组,你可以使用reduce
let sorted_nums = ['1,3', '4,2']
.map(item => item.split(',')) // [['1', '3'], ['4', '2']]
.reduce((a, b) => a.concat(b)) // ['1', '3', '4', '2']
.sort() // ['1', '2', '3', '4']
其他回答
使用Array.prototype.concat.apply来处理多个数组的连接:
var resultArray = Array.prototype.concat.apply([], arrayOfArraysToConcat);
例子:
var a1 = [1, 2, 3],
a2 = [4, 5],
a3 = [6, 7, 8, 9];
Array.prototype.concat.apply([], [a1, a2, a3]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
现在我们可以使用ES6 Spread组合多个数组。 不要使用concat()来连接数组,而是尝试使用spread语法将多个数组组合成一个扁平数组。 例如:
var a = [1,2];
var b = [3,4];
var c = [5,6,7];
var d = [...a, ...b, ...c];
// resulting array will be like d = [1,2,3,4,5,6,7]
这是一个函数,通过它可以连接多个数组
function concatNarrays(args) {
args = Array.prototype.slice.call(arguments);
var newArr = args.reduce( function(prev, next) {
return prev.concat(next) ;
});
return newArr;
}
的例子,
console.log(concatNarrays([1, 2, 3], [5, 2, 1, 4], [2,8,9]));
将输出
[1,2,3,5,2,1,4,2,8,9]
如果你正在通过map/filter/sort等管道输出结果,并且你想连接数组的数组,你可以使用reduce
let sorted_nums = ['1,3', '4,2']
.map(item => item.split(',')) // [['1', '3'], ['4', '2']]
.reduce((a, b) => a.concat(b)) // ['1', '3', '4', '2']
.sort() // ['1', '2', '3', '4']
其中'n'是数组的个数,可能是数组的数组…
Var答案= _。Reduce (n, function(a, b){返回a.concat(b)})