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?
Have a fresh tip? Share with Coderwall community!
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