Leonid Leonid - 6 months ago 20
Javascript Question

What is the most efficient way to concatenate N arrays in JavaScript?

What is the most efficient way to concatenate N arrays of objects in

JavaScript
?

The arrays are mutable, and the result can be stored in one of the input arrays.

Answer

If you're concatenating more than two arrays, concat() is the way to go for convenience and likely performance.

var a = [1, 2], b = ["x", "y"], c = [true, false];
var d = a.concat(b, c);
console.log(d); // [1, 2, "x", "y", true, false];

For concatenating just two arrays, using push.apply() can be used instead for the case of adding elements from one array to the end of another without producing a new array. With slice() it can also be used instead of concat() but there appears to be no performance advantage from doing this.

var a = [1, 2], b = ["x", "y"];
a.push.apply(a, b);
console.log(a); // [1, 2, "x", "y"];

However, it seems that for large arrays (of the order of 100,000 members or more), this technique can fail. For such arrays, using a loop is a better approach. See http://stackoverflow.com/a/17368101/96100 for details.