JavaScript 2D Array

Harshit Jindal Oct 12, 2023
  1. Array Constructor to Create 2D Array in JavaScript
  2. Array Literal Notion to Create 2D Array in JavaScript
  3. the Array.from() Method to Create 2D Array in JavaScript
  4. the Array.prototype.map() Method to Create 2D Array in JavaScript
JavaScript 2D Array

This tutorial introduces how to declare a two-dimensional array in JavaScript. In two dimensional array, the items are organized as a matrix in the form of rows and columns. It is like an array whose elements are one-dimensional arrays.

Array Constructor to Create 2D Array in JavaScript

We use the array constructor to create an empty array of the given length. We can then use a for loop to create an array for each element.

const m = 4;
const n = 5;

let arr = new Array(m);

for (var i = 0; i < m; i++) {
  arr[i] = new Array(n);
}

console.log(arr);

Output:

Array [ [ null, null, null, null, null ], [ null, null, null, null, null ], [ null, null, null, null, null ], [ null, null, null, null, null ] ]

Array Literal Notion to Create 2D Array in JavaScript

We can use the literal notation method to create 2D arrays in JavaScript.

const m = 4;
const n = 5;
let arr = [];

for (var i = 0; i < m; i++) {
  arr[i] = [];
}

console.log(arr);

Output:

Array [ [], [], [], [] ]

the Array.from() Method to Create 2D Array in JavaScript

The Array.from() method returns an array object from any JavaScript object.

const m = 4;
const n = 5;

let arr = Array.from(Array(m), () => new Array(n));

console.log(arr);

Output:

Array [ [ null, null, null, null, null ], [ null, null, null, null, null ], [ null, null, null, null, null ], [ null, null, null, null, null ] ]

the Array.prototype.map() Method to Create 2D Array in JavaScript

The Array.map() method also helps create a 2D array by mapping array elements to an empty array.

const m = 4;
const n = 5;
let arr = Array(m).fill().map(() => Array(n));
console.log(arr);

Output:

Array [ [ null, null, null, null, null ], [ null, null, null, null, null ], [ null, null, null, null, null ], [ null, null, null, null, null ] ]
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

Related Article - JavaScript Array