Home > Software engineering >  The modifying in nested array
The modifying in nested array

Time:01-07

I created an nested array with empty array for each item. I want to input the data to each index with push method. But instead of inserting to each item the data is filled to all item. Could someone help me explain this behavior? Thanks

let input = new Array(4).fill([]);
let data = [[0,1],[3,2],[2,1]];
for(let i = 0; i < data.length; i  ){
   const key = data[i][1]
   const value = data[i][0]
   input[key].push(value)
}
console.log(input)

CodePudding user response:

It is related to how Array fill behaves. When you pass an object (an empty array in this case) as the parameter, all of your elements have the same reference.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#value

CodePudding user response:

Array is an object.. you are filling the array with same object and pushing to same object reference

let input = new Array();
let data = [[0,1],[3,2],[2,1]];
for(let i = 0; i < data.length; i  ){
   input[key] = input[key] || [];
   const key = data[i][1]
   const value = data[i][0]
   input[key].push(value)
}
console.log(input)

CodePudding user response:

You've filled the array with the same empty array

Think of it like this

const a = []
const b = new Array(4).fill(a)

a is inserted into the array four times and any index of b is a reference to a.

CodePudding user response:

Arrays that was filled inside input variable is the same and when you change one of this array you change all linked arrays also. You can read more about it here: https://javascript.info/object-copy

let input = new Array(4).fill([]);
let a = []
let b = []
let c = a

console.log(input[0] === input[1]) ---> true
console.log(a === b) ---> false
console.log(a === c) ---> true
  • Related