Multidimensional array

A multidimensional array is an array that contains one or more arrays as its elements. In other words, it's an array of arrays. A one-dimensional array is essentially a list of values, whereas a multidimensional array is like a table or matrix with rows and columns.

In JavaScript, a multidimensional array is created by nesting one or more arrays inside another array. Each array inside the main array is considered a "dimension". For example, a two-dimensional array could be thought of as a table with rows and columns, where each row is an array of values and the entire table is an array of rows.

Here's an example of creating a two-dimensional array in JavaScript:

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

In this example, table is a two-dimensional array with three rows and three columns. The first row is [1, 2, 3], the second row is [4, 5, 6], and the third row is [7, 8, 9].

To access an element in a multidimensional array, you can use multiple indexes. For example, to access the element in the second row and third column of table, you would use table[1][2], because the indexes start at 0.

Here's an example of accessing elements in the table array:

console.log(table[0][0]); // Output: 1
console.log(table[1][2]); // Output: 6
console.log(table[2][1]); // Output: 8

You can also create arrays with more than two dimensions. For example, a three-dimensional array could be used to represent a cube or a three-dimensional grid. However, working with arrays that have more than two dimensions can become increasingly complex, and it's generally recommended to use them sparingly.

You can use nested loops to iterate over each element of a multidimensional array in JavaScript.

Here's an example of using nested loops to access each element in a two-dimensional array:

let arr = [[1, 2], [3, 4], [5, 6]];

for(let i = 0; i < arr.length; i++) {
  for(let j = 0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}

In this example, we have a two-dimensional array arr with three sub-arrays, each containing two elements. The outer loop iterates over the sub-arrays using the array's length property, while the inner loop iterates over each element of the current sub-array using the sub-array's length property.

Inside the loops, we can access each element of the array using its index. The index of the outer loop corresponds to the current sub-array, while the index of the inner loop corresponds to the current element within that sub-array.

By using nested loops, we can access each element of the multidimensional array and perform any necessary operations on it.

Last updated