Last Updated: February 25, 2016
·
2.679K
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside