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?
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?
Share Improve this question asked Jun 20, 2017 at 17:58 AturSamsAturSams 7,95218 gold badges67 silver badges105 bronze badges 05 Answers
Reset to default 9You 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);
The magic part could be:
arr.splice(0, arr.length, 4, 5, 6);
var arr = [1, 2, 3];
var b = arr;
b == arr; // true
arr.splice(0, arr.length, 4, 5, 6);
console.log(b);
console.log(arr);
console.log(arr === b);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you already have the replacing array in a variable (let's say repl = [4, 5, 6]
), then use the rest parameters syntax:
arr.splice(0, arr.length, ...repl);
var arr = [1, 2, 3];
var b = arr;
var repl = [4, 5, 6];
b == arr; // true
arr.splice(0, arr.length, ...repl);
console.log(b);
console.log(arr);
console.log(arr === b);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here's one way:
var arr = [1, 2, 3];
var b = arr;
console.log(`b == arr, b
`, b == arr, b.join());
var c = magic(arr, [4, 5, 6]);
console.log(`b == arr, b
`, b == arr, b.join());
console.log(`c == arr, c
`, c == arr, c.join());
function magic(to, from) {
// remove elements from existing array
var old = to.splice(0);
for (var i = 0; i < from.length; i++) {
to[i] = from[i];
}
return old;
}
This implementation returns a copy of the old elements that were originally in the array.
Copy the new values over the old ones.
function magic(arr, newvals) {
for (let i = 0; i < newvals.length; i++) arr[i] = newvals[i];
arr.length = newvals.length;
}
function replaceArrValues(arrRef, newValues)
{
arrRef.length = 0; // clear the array without losing reference
newValues.forEach(x => arrRef.push(x));
}