Multi-Dimensional Array in Javascript


Basically, multi-dimension arrays are used if you want to put arrays inside an array. Let's take an example. Say you wanted to store every 6 hour's temperature for every weekday. You could do something like:

let monday = [35, 28, 29, 31];
let tuesday = [33, 24, 25, 29];
//...

This is a good place to use a multidimensional array instead. A multidimensional array is nothing but an array of arrays. If we take forward our example, each row will represent a day while each entry in the row will represent a temp entry. For example,

let temps = [
   [35, 28, 29, 31],
   [33, 24, 25, 29]
];

You can chain array access. For example, if you want the 3rd element in the second row, you could just query for temps[1][2]. Note that the order is rows than columns. You can iterate these arrays using multiple for loops. For example,

let temps = [
   [35, 28, 29, 31],
   [33, 24, 25, 29]
];
for (let i = 0; i < 2; i++) {
   console.log("Row #" + i) for (let j = 0; j < 4; j++) {
      console.log(i, j, temps[i][j])
   }
}

This will give the output −

Row #0
0 0 35
0 1 28
0 2 29
0 3 31
Row #1
1 0 33
1 1 24
1 2 25
1 3 29

Multidimensional arrays can have more than 2 dimensions as well. Mostly 2 dimensions will suffice, though some places where you can use 3 dimensions are during 3D operations, physics calculations, etc.

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 15-Jun-2020

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements