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.
Written by Joshua Croad
Related protips
1 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
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#