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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With