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?