1

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
}

Result: enter image description here

Ismoil Shokirov
  • 2,213
  • 2
  • 16
  • 32
  • 4
    `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. So `rotate2[0] === rotate2[1]` because `rotate2[0]` and `rotate2[1]` refer to the **same** array. You might want `const rotate2 = Array.from({length: theLength}, () => []);`. – T.J. Crowder May 04 '22 at 12:10
  • 2
    I got your point, so rotate2[0] and rotate2[1] are pointing to the same memory location. Thank you – Ismoil Shokirov May 04 '22 at 12:37

0 Answers0