Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to concatenate N arrays?

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.

like image 941
Leonid Avatar asked Feb 22 '11 15:02

Leonid


People also ask

How do you concatenate 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.

How do you append multiple arrays into an array of arrays?

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.

Which method is used to merge two or more array?

concat() The concat() method is used to merge two or more arrays.


2 Answers

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.

like image 91
Tim Down Avatar answered Oct 07 '22 18:10

Tim Down


[].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.)

like image 40
ninjagecko Avatar answered Oct 07 '22 16:10

ninjagecko