JavaScript Multi-dimensional Arrays

JavaScript Tutorial

JavaScript Multi-dimensional Arrays

Multi-dimensional array ka matlab hota hai array ke andar array. JavaScript me ye commonly 2D array (rows × columns) ke form me use hota hai, jaise table, matrix, grid, etc.


1️⃣ What is a Multi-dimensional Array?

let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

👉 Yahan:

  • matrix → main array

  • Har element ek inner array hai

  • Ye structure 3 × 3 matrix jaisa hai


2️⃣ Accessing Elements

Syntax

array[rowIndex][columnIndex]

Example

let matrix = [
[10, 20],
[30, 40]
];
console.log(matrix[0][0]); // 10
console.log(matrix[0][1]); // 20
console.log(matrix[1][0]); // 30
console.log(matrix[1][1]); // 40


3️⃣ Modify Elements

let matrix = [
[1, 2],
[3, 4]
];
matrix[0][1] = 99;

console.log(matrix);
// [ [1, 99], [3, 4] ]


4️⃣ Loop Through Multi-dimensional Array

Using for loop

let matrix = [
[1, 2, 3],
[4, 5, 6]
];
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}


Using forEach

matrix.forEach(row => {
row.forEach(value => {
console.log(value);
});
});

5️⃣ Add Data in Multi-dimensional Array

Add a new row

matrix.push([7, 8, 9]);

Add a new column value

matrix[0].push(10);

6️⃣ 3-Dimensional Array Example

let cube = [
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
];
console.log(cube[1][0][1]); // 6


7️⃣ Real-Life Examples

✔ Marks Table

let marks = [
["Math", 85],
["Science", 90],
["English", 88]
];
console.log(marks[1][0]); // Science
console.log(marks[1][1]); // 90


✔ Tic-Tac-Toe Board

let board = [
["X", "O", "X"],
["O", "X", "O"],
["X", "", "O"]
];

8️⃣ Important Points to Remember

  • JavaScript me true matrix nahi hoti, sirf array of arrays

  • Har row ka size same hona zaruri nahi

  • Dynamic data ke liye useful

You may also like...