Replace array elements without losing reference?

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);

Tags:

Javascript