No announcement
 

Multi-dimensional Arrays

In JavaScript, a multi-dimensional array is an array of arrays. It allows you to store data in a grid-like structure, where each element of the outer array contains an inner array representing a row of data.

Example:

multi_dimensional_array.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Multi-dimensional Array Example</title>
</head>
<body>

<h2>JavaScript Multi-dimensional Array:</h2>
<script>
// Multi-dimensional Array
let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[0][1]); // Output: 2
console.log(matrix[2][0]); // Output: 7
</script>

</body>
</html>

Output
2 7

In this example, we created a multi-dimensional array called matrix. It contains three inner arrays, each representing a row of data. The first row [1, 2, 3], the second row [4, 5, 6], and the third row [7, 8, 9].

To access individual elements in a multi-dimensional array, you use the square bracket notation [rowIndex][columnIndex]. In our example, matrix[0][1] accesses the element at row 0 and column 1, which is 2. Similarly, matrix[2][0] accesses the element at row 2 and column 0, which is 7.

Working with Multi-dimensional Arrays:

You can use loops, such as nested for loops, to traverse and manipulate the elements of a multi-dimensional array.

Example:

multi_array_looping.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Loop through Multi-dimensional Array Example</title>
</head>
<body>

<h2>JavaScript Loop through Multi-dimensional Array:</h2>
<script>
// Multi-dimensional Array
let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Loop through the matrix and log each element
for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(matrix[i][j]);
  }
}
</script>

</body>
</html>

Output
1 2 3 4 5 6 7 8 9

In this example, we used nested for loops to loop through each row and column of the matrix multi-dimensional array. The loop logs each element to the console.

Multi-dimensional arrays are helpful when dealing with tabular data, game boards, or any situation where you need to represent data in a structured grid-like format. They provide a convenient way to organize and access data in a two-dimensional format and are widely used in various programming tasks.