2

I have an array A and a function that generates me an array B

var A = ["test"];
var B = ["hello", "world"];
var C = A;

How to make it so A = B (contains all and only the values in B) without changing its reference, so C also contains all and only the values in B.

IggY
  • 3,005
  • 4
  • 29
  • 54
  • 4
    possible duplicate of: http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript – guysigner Feb 05 '16 at 08:05
  • possible duplicate http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items – Kaushik Feb 05 '16 at 08:06
  • If you set C = A first, then setting A = (Anything) won't affect C in any condition. – Ali Feb 05 '16 at 08:08
  • @remdevtec that's not quite what OP is asking. I believe he is specifically asking how to change the underlying pointer of `A` to point to `B` *after* `C` has already been pointed to `A`. So, after changing the reference, printing `C` would in fact print the contents of `B`. I'm fairly sure this isn't possible based on the quesiton/answer http://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value – Matthew Herbst Feb 05 '16 at 08:08
  • remdevtex and Unknown users, the suggested duplicates are not duplicates. They do not apply to keeping the same array and make a copy instead. – Arnaud Weil Feb 05 '16 at 08:19

1 Answers1

5

I'd suggest:

A.splice(0);
A.push.apply(A, B);

Splice will remove all of the items from A. Push will add the items from B to A. Except push takes an argument list, not an array, so we call apply in order to convert the array into arguments.

Working example here.

Arnaud Weil
  • 2,324
  • 20
  • 19