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
}