在JavaScript中连接N个对象数组的最有效的方法是什么?

数组是可变的,结果可以存储在一个输入数组中。


当前回答

如果只有两个数组要连接,并且实际上需要追加其中一个数组,而不是创建一个新数组,则应该使用push或循环。

基准:https://jsperf.com/concat-small-arrays-vs-push-vs-loop/

其他回答

如果你有一个数组的数组,想要连接到一个数组的元素,尝试以下代码(要求ES2015):

let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = [];
for (let arr of arrOfArr) {
    newArr.push(...arr);
}

console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];

或者如果你喜欢函数式编程

let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = arrOfArr.reduce((result,current)=>{
    result.push(...current);
    return result;
});

console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];

或者使用ES5语法更好,没有展开操作符

var arrOfArr = [[1,2,3,4],[5,6,7,8]];
var newArr = arrOfArr.reduce((result,current)=>{
    return result.concat(current);
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];

如果你不知道不,这种方法很方便。数组的。

使用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]

对于使用ES2015 (ES6)的用户

你现在可以使用扩展语法来连接数组:

const arr1 = [0, 1, 2],
      arr2 = [3, 4, 5];

const result1 = [...arr1, ...arr2]; // -> [0, 1, 2, 3, 4, 5]

// or...

const result2 = [...arr2, ...arr1]; // -> [3, 4, 5, 0, 1, 2]

这是一个函数,通过它可以连接多个数组

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']