I have two arrays, one comes as a reference (parameter) from a function, and the other is created as part of the function - exactly the same scenario as described here:
Add two arrays without using the concat method
I was using the push.apply() method as per the suggestion above, but can someone please explain to me, why I can't use concat() to merge two arrays if the array is sent into the function as a reference?
I have two arrays, one comes as a reference (parameter) from a function, and the other is created as part of the function - exactly the same scenario as described here:
Add two arrays without using the concat method
I was using the push.apply() method as per the suggestion above, but can someone please explain to me, why I can't use concat() to merge two arrays if the array is sent into the function as a reference?
Share Improve this question edited May 23, 2017 at 11:50 CommunityBot 11 silver badge asked May 21, 2013 at 21:12 TamasTamas 11.2k15 gold badges51 silver badges79 bronze badges 1- Have a look at the link. It doesn't matter what I do, it's exactly the same as shown on the other page. – Tamas Commented May 21, 2013 at 21:17
3 Answers
Reset to default 10Refer to Array.concat on MDN:
Any operation on the new array will have no effect on the original arrays, and vice versa.
This makes it behave differently from Array.push.apply
which will mutate the original Array object - the return value of Array.concat
must be used. Otherwise, it works as explained in the MDN link above.
If you use concat
the original array will be unmodified. If you have a reference to it you wont see the new elements.
var arr1 = [ "a", "b" ];
var arr2 = [ "c", "d" ];
arr1.push.apply(arr1, arr2);
Basically does this:
[ "a", "b" ].push("c", "d");
apply
turns an array into a list of arguments. The first argument to apply
is the context
by the way, arr1
in this case since you want the push to apply to arr1
.
You can use concat
:
var arr1 = [ "a", "b" ];
var arr2 = [ "c", "d" ];
var arr3 = arr1.concat(arr2);
This leaves the original arr1
as it was. You've created a new array that has both arr1
and arr2
elements in it. If you have a reference to the original arr1
it will be unmodified. That might be a reason to not want to use concat
.
Let's say we have 2 arrays "a" and "b". Array.concat
method will return new instance of Array
"c" which represents concatenation between a and b without any mutation of a or b. Array.push
return last index of pushed element and mutate this
instance.
Since ES6 (or 15, not sure) it's possible to unpack parameters and you can use push to concatenate (without harmful code) as well
a = [1,2,3,4]; // a=[1,2,3,4];
b = [5,6,7,8]; // b=[5,6,7,8];
a.push(...b) // a=[1,2,3,4,5,6,7,8]; b=[5,6,7,8]