Array.fill() doesn't work for 2D arrays.
I was solving an algorithm where I need to rotate a matrix to 90degrees.
Using map() and Array().fill() completely changes the actual result. I am confused what could be the reason for that
function rotate90(matrix) {
const len = matrix.length
const rotate = matrix.map(_ => [])
const rotate2 = new Array(len).fill([])
console.log('rotate', rotate);
console.log('rotate2', rotate2);
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
rotate[j][len - 1 - i] = matrix[i][j]
rotate2[j][len - 1 - i] = matrix[i][j]
}
}
console.log("using map()")
for (let i = 0; i < len; i++) {
console.log(rotate[i])
}
console.log("using new Array()")
for (let i = 0; i < len; i++) {
console.log(rotate2[i])
}
return rotate
}

matrix.map(_ => [])creates an array with separate arrays for each of its elements.new Array(len).fill([])creates an array with one array reused for all of its elements. Sorotate2[0] === rotate2[1]becauserotate2[0]androtate2[1]refer to the same array. You might wantconst rotate2 = Array.from({length: theLength}, () => []);.