Last Updated: February 25, 2016
·
2.46K
· joshcroad

Merging Two Arrays in JavaScript

Recently I have needed to merge two arrays in Node, much like the PHP function array_merge(). This seemed trivial, with the method:

Array.prototype.concat(value1, value2, ..., valueN);

However, arr.concat(value1) returns a new array, containing copies of values from the original arrays.

I have found this is not always a great option, especially if the arrays are large, or memory allocation is limited.

A much better option can be achieved by using the Function.prototype.apply();.

arr.push.apply(arr, arr2);

This will efficiently combine both arrays.

1 Response
Add your response

Thanks for sharing. I never thought of using push that way. Have you got some numbers or benchmarks to share as well?

over 1 year ago ·