Is there a built in way to append one list into another like so:
var a = [1,2,3];
a.append([4,5]);
// now a is [1,2,3,4,5];
concat()
does something similar but returns the result. I want something that modifies the existing list like push()
Is there a built in way to append one list into another like so:
var a = [1,2,3];
a.append([4,5]);
// now a is [1,2,3,4,5];
concat()
does something similar but returns the result. I want something that modifies the existing list like push()
push
will work, but you also need to use apply
.
var a = [1,2,3];
a.push.apply(a, [4,5])
If you are using ES6 you can use the spread operator
eg :-
listOne = [1,2,3]
listTwo = [4,5,6]
listTwo.push(...listOne)
var list = [1, 2];
People already showed you how to do this with:
list.push.apply(list, [3, 4]);
list = list.concat([4, 5]);
But I want to tell about ES6 spread operator: list.push(...[3, 4]);
.
Keep in mind that currently not many browsers support it (you can use transpilers).
Because I just wrote a web application where a lot of arrays have to be concatenated and where performance is critical, I tested which method is fastest in this jsperf. The results are quite interesting.
In my test, I add 10 elements to a list or array of 10,000 elements.
Here are the test cases, from fastest to slowest. Results are measured in Chrome 62, but Firefox 47 performs similarly:
LinkedList.prototype.concat
: 90,313,485 ops/sec
list.concat(concatList);
// This function has to change only 1-2 refences
Array.prototype.push
in a for loop: 3,794,962 ops/sec
for (var i = 0, len = concatArr.length; i < len; i++) {
array.push(concatArr[i]);
}
// Probably fastest in real life
Array.prototype.push.apply
: 2,193,469 ops/sec
array.push.apply(array, concatArr);
Array.prototype.concat
: 22,701 ops/sec
array = array.concat(concatArr);
Unfortunately, the LinkedList
version doesn't work if you want to concat an array/list to multiple LinkedList
s. It also has no benefit if an array has to be copied to a LinkedList
before every concat operation. So, for me, the winner is the for loop.
One reason to not use Array.prototype.push.apply
is that it fails if the concatenated array is too big. According to this answer, the concatenated array can't have more than 500,000 elements in Firefox and 150,000 elements in Chrome.
I excluded the spread operator because it is not supported by all browsers. In Chrome, it's about as fast as Array.prototype.push.apply
, in Firefox it is a bit slower.
How about this:
var a = [1, 2, 3];
a = a.concat([4, 5]);
// a is now [1, 2, 3, 4, 5]