How to create multidimensional array in JavaScript?
In JavaScript, a multi-dimensional array can be created by nesting arrays. For example, to create a 2-dimensional array with 2 rows and 3 columns, you can use the following code:
let multiArray = [[1, 2, 3], [4, 5, 6]];
You can also use a loop to create a multi-dimensional array of a specific size, like this:
let rows = 3; let cols = 4; let multiArray = new Array(rows); for (let i = 0; i < rows; i++) { multiArray[i] = new Array(cols); }
You can also use Array.from() method to create multi-dimensional array:
let multiArray = Array.from({length: rows}, () => new Array(cols));
In this example, multiArray is a multi-dimensional array. You can access its elements like this:
let element = multiArray[0][1];
You can also use map() method to create a Javascript multi-dimensional array:
let multiArray = Array(rows).fill().map(() => Array(cols));
Disclaimer:
As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.