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.

5
  • 4
    possible duplicate of: stackoverflow.com/questions/7486085/… Commented Feb 5, 2016 at 8:05
  • possible duplicate stackoverflow.com/questions/1584370/… Commented Feb 5, 2016 at 8:06
  • If you set C = A first, then setting A = (Anything) won't affect C in any condition. Commented Feb 5, 2016 at 8: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 stackoverflow.com/questions/6605640/… Commented Feb 5, 2016 at 8: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. Commented Feb 5, 2016 at 8:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's not obvious what the A.push.bind(A, B); line is supposed to do.
Sorry, I had an error, just fixed: you need to call apply, not bind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.