What is the most efficient way to concatenate N arrays?
[].concat.apply([], [array1, array2, ...])
edit: proof of efficiency: http://jsperf.com/multi-array-concat/7
edit2: Tim Supinie mentions in the comments that this may cause the interpreter to exceed the call stack size. This is perhaps dependent on the js engine, but I've also gotten "Maximum call stack size exceeded" on Chrome at least. Test case: [].concat.apply([], Array(300000).fill().map(_=>[1,2,3]))
. (I've also gotten the same error using the currently accepted answer, so one is anticipating such use cases or building a library for others, special testing may be necessary no matter which solution you choose.)
For people using ES2015 (ES6)
You can now use the Spread Syntax to concatenate arrays:
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]
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, the fact that push
accepts multiple arguments consisting of elements to add to the array can be used instead to add 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"];
In ECMAScript 2015 and later, this can be reduced even further to
a.push(...b)
However, it seems that for large arrays (of the order of 100,000 members or more), the technique passing an array of elements to push
(either using apply()
or the ECMAScript 2015 spread operator) can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.