IggY
IggY

Reputation: 3135

Fastest way to do Array A = Array B without changing the reference of A

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.

Upvotes: 2

Views: 85

Answers (1)

Arnaud Weil
Arnaud Weil

Reputation: 2502

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.

Upvotes: 5

Related Questions