user203212546 user203212546 - 2 months ago 7
Javascript Question

When does an array update vs. creating new values?

I have a [Edit: JavaScript] code that uses a sub-array

dataSelectedArray
that tracks from my main data set
mainArray
. The main data is stored as an array of arrays.

mainArray = [ [1,2,3],[3,4,2],[5,1,0] ];
dataSelectedArray=[];
for (var i=0; i<dataArray.length; i++) {
if ( someLogic ) {
dataSelectedArray.push(mainArray[i]);
}
}


Thus,
dataSelectedArray
holds pointers to the values stored by
mainArray
. Later, I need to update
mainArray
by replacing it with data from
updatedData
. I need
dataSelectedArray
to also be updated. I can think of two ways to do this: update each mini-array as a set, or update each component.



var mainArray = [ [1,2,3],[3,4,2],[5,1,0] ];
var dataSelectedArray=[];
for (var i=0; i<mainArray.length; i++) {
if ( i<2 ) {
dataSelectedArray.push(mainArray[i]);
}
}

updatedData = [ [ 1,0,0],[7,4,2] ];
for (var index= 0; index < updatedData.length; index++) {
// this doesn't update dataSelectedArray
mainArray[index] = updatedData[index];
}
console.log(mainArray[0]);
console.log(dataSelectedArray[0]);







var mainArray = [ [1,2,3],[3,4,2],[5,1,0] ];
var dataSelectedArray=[];
for (var i=0; i<mainArray.length; i++) {
if ( i<2 ) {
dataSelectedArray.push(mainArray[i]);
}
}

updatedData = [ [ 1,0,0],[7,4,2] ];
for (var index= 0; index < updatedData.length; index++) {
// this *does* update dataSelectedArray
mainArray[index][0] = updatedData[index][0];
mainArray[index][1] = updatedData[index][1];
mainArray[index][2] = updatedData[index][2];
}
console.log(mainArray[0]);
console.log(dataSelectedArray[0]);





The first method doesn't update
dataSelectedArray
...why not? And is there a shorter (one-liner) way to do the second method?

Answer

When you do:

dataSelectedArray.push(mainArray[i]);

dataSelectedArray contains a reference to the sub-array. This is not a reference to the location in mainArray where the original reference came from. So reassigning mainArray[i] has no effect on the value in dataSelectedArray.

It's no different from when you have multiple variables referring to the same array:

var a = [1, 2, 3];
var b = a; // a and b now refer to the same array
b[1] = 6;
console.log(a[1]); // Outputs 6
b = [7, 8, 9]; // b now refers to a different array
console.log(a[1]); // Still 6 -- a hasn't been modified