Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace array elements without losing reference?

Tags:

javascript

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?

like image 953
AturSams Avatar asked Jun 20 '17 17:06

AturSams


1 Answers

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);
like image 54
Nina Scholz Avatar answered Sep 26 '22 16:09

Nina Scholz