JavaScript 2D Array
- Array Constructor to Create 2D Array in JavaScript
- Array Literal Notion to Create 2D Array in JavaScript
-
the
Array.from()
Method to Create 2D Array in JavaScript -
the
Array.prototype.map()
Method to Create 2D Array in JavaScript
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 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.
LinkedInRelated Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript