DEV Community

Bruce Axtens
Bruce Axtens

Posted on

How to pre-dimension a 2D array in JavaScript

I learned how to pre-fill/pre-dimension a 2D array! It was part of an Exercism challenge.

I had tried things like

var a = Array(3).fill(Array(2).fill(0))
Enter fullscreen mode Exit fullscreen mode

but when you do something like

a[0][1] = "dog";
Enter fullscreen mode Exit fullscreen mode

you get an array that looks like

[[0,"dog"], [0,"dog"], [0,"dog"]]
Enter fullscreen mode Exit fullscreen mode

So what one has to do is to Array(3).fill(0) and then .map the array to another Array(2).fill(0) as per the following fragment from my Exercism solution:

rotate(array) {
    const [rowMax, colMax] = [array.length, array[0].length];
    const result = Array(colMax)
      .fill(0)
      .map(() => Array(rowMax).fill(0));
    for (let col = 0; col < rowMax; col++) {
      for (let row = 0; row < colMax; row++) {
        result[row][col] = array[col][row];
      }
    }
    return result;
  }
Enter fullscreen mode Exit fullscreen mode

specifically the

Array(colMax)
      .fill(0)
      .map(() => Array(rowMax).fill(0));
Enter fullscreen mode Exit fullscreen mode

part

Discussion (0)