loading...

How to pre-dimension a 2D array in JavaScript

bugmagnet profile image Bruce Axtens ・1 min read

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))

but when you do something like

a[0][1] = "dog";

you get an array that looks like

[[0,"dog"], [0,"dog"], [0,"dog"]]

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;
  }

specifically the

Array(colMax)
      .fill(0)
      .map(() => Array(rowMax).fill(0));

part

Posted on by:

bugmagnet profile

Bruce Axtens

@bugmagnet

Programmed Canon Canola calculators in 1977. Assorted platforms and languages ever since. Assisting with HOPL.info. I am NOT looking for work -- I've got more than enough to do.

Discussion

markdown guide