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.
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
concat() The concat() method is used to merge two or more arrays.
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.
[].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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With