Non equals arrays changing values at same time javascript

Please check the following…

var arr = [["test", 1], ["test", 3], ["test", 5]]
var otherArr = arr.slice(0) //should be a new array with a copy of arr

When i evaluate arr === otherArr the result is FALSE.

When i do the following, trying to change first array value:

otherArr[0][1] = otherArr[0][1] + 5;

it also changes the original array (arr) :scream:

arr[0][1] === otherArr[0][1] evaluates to TRUE

but arr === otherArr evaluates to FALSE

Please help me understand this, and tell me how i can avoid it to happen

This is a tricky one alright. Arrays store values by reference. What this means is that each array references place in memory on your machine. What you have here is an array of arrays.

The outer array refers to a piece of memory but so do the inner arrays. var otherArr = arr.slice(0) changes the reference to the outer array but not the inner arrays. This is why arr[0][1] === otherArr[0][1] is true!

Making copies of nested arrays or nested object is a little messy because of this. If you need a new copy you could do something like this:

var arr = [["test", 1], ["test", 3], ["test", 5]];
var otherArr = arr.map(function(innerArray){
  return [...innerArray];
});

console.log(arr[0] === otherArr[0]); // will be false

but this way

var arr = [["test", 1], ["test", 3], ["test", 5]]
var otherArr = arr.slice(0)

console.log(arr[0] === otherArr[0]);  // will be true as the slice only copies the outer references

You have to loop through each level and copy the values to a new array (a new reference).

[...innerArray] is the same thing as doing innterArray.slice(0)

1 Like

Thanks a lot! Solved and learned! :+1::+1:

1 Like