DEV Community

Bruce Axtens
Bruce Axtens

Posted on

1 2

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay