Multidimensional arrays in JavaScript

This tutorial will explain how to create, access, and modify elements in a multidimensional array. In the example here, we will work with a 2D (two dimensional) array in JavaScript.

We already know that an array is a better way of storing several related values than creating multiple variables. But what if we want to store several characteristics for each element in an array? Well, we can use two dimensional arrays for that! Watch the video below to find out more and then scroll down to see the code.

In the example code below, we have a two dimensional array that stores several people in an the array. For each person, the array also stores characteristics about them including their name, age, and gender. In other words, there are elements inside elements in the array.

If we wanted to access the first element in an array we would usually use the code arrayname[0]. If we want to access the first element inside the first element of the array, we would access it using the code arrayname[0][0]. Basically, there are two dimensions in the array. We access the first element in the first dimension, and the first element from its second dimension.

Check out the code below to see how you can create a 2D array, access elements inside it, and modify values in the array.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Multidimensional Arrays</title>
 
 <script type="text/javascript">
 
 // This is 2 dimensional array which stores name, age, and gender for different people
 
 var people = [
 ["John", 16, "Male"],
 ["Mary", 42, "Female"],
 ["Jason", 21, "Male"]
 ];
 
 // Remember that array elements start counting from 0
 // To access the name of the first person in the array, we need to access people[0][0]
 document.write(people[0][0] + "<br/>");
 
 // This will access the age of the second person in the array:
 document.write(people[1][1] + "<br/>");
 
 // This will access the gender of the third person in the array:
 document.write(people[2][2] + "<br/>");
 
 // To change the age of the third person (Jason) in the array:
 people[2][1]=22;
 document.write(people[2][1] + "<br/>");
 
 // To add an extra person to the array:
 people[3]=["Sarah", 36, "Female"];
 
 // This will display all elements (name, age, gender) inside the fourth array element
 document.write(people[3]);
 
 </script>
 
</head>
<body>
 
</body>
</html>

The code above will produce output that looks like this:

Screen Shot 2015-03-20 at 10.22.59 pm


Next tutorial: 
If statements