zehelvion zehelvion - 1 month ago 6
Javascript Question

Replace array elements without losing reference?

How does one replace all elements of an array without losing references?

var arr = [1, 2, 3];
var b = arr;
b == arr; // true
magic(arr, [4, 5, 6]);
b == arr; // should return true


One way of doing it is by popping and pushing. Is there a clean way?

Answer Source

You could splice the old values and append the new values.

function magic(reference, array) {
    [].splice.apply(reference, [0, reference.length].concat(array));
}

var arr = [1, 2, 3],
    b = arr;

console.log(b === arr); // true
magic(arr, [4, 5, 6]);
console.log(b === arr); // should return true

console.log(arr);

Another way, is to use Object.assign. This requires to set the length of the array, if it is smaller than the original array.

function magic(reference, array) {
    Object.assign(reference, array, { length: array.length });
}

var arr = [1, 2, 3],
    b = arr;

console.log(b === arr); // true
magic(arr, [4, 5, 6, 7]);
console.log(b === arr); // should return true

console.log(arr);