Reputation: 950
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)
Upvotes: 1
Views: 52
Reputation: 66
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
Upvotes: 0
Reputation: 2661
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.
Upvotes: 1
Reputation: 1523
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
Upvotes: 1
Reputation: 414
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)
Upvotes: 1