Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating 2D arrays using new Array in Javascript [duplicate]

I was trying out a question on Hackerrank where I needed to create an array of array (basically 2d arrays).

My go-to one liner would be const counter = new Array(4).fill([]) However, I realized that it would create a 2D array but applying any function to the array would cause it to apply to all the elements.

let count = new Array(4).fill([])
count[0].push("Test")
console.log(JSON.stringify(count))

The outcome would be all the sub-arrays having the same value of "Test" inside them.

The final solution would be:

let count = Array.from(Array(4), () => new Array());
count[0].push("Test")
console.log(JSON.stringify(count))

May I ask the reason why it's not working as expected?

like image 438
MrYanDao Avatar asked Mar 17 '26 07:03

MrYanDao


1 Answers

Because .fill() takes the argument and, if it's an object, it copies the reference to that object into every index of the new array. Since in fact [] is an object, your new array ends up being filled with references to the same array.

From the docs:

If the first parameter is an object, it will copy its reference and fill the array with references to that object.

like image 158
Sebastian Kaczmarek Avatar answered Mar 19 '26 20:03

Sebastian Kaczmarek