
Two-dimensional and multi-dimensional arrays
At the beginning of this chapter, we used a temperature measurement example. We will now use this example one more time. Let's consider that we need to measure the temperature hourly for a few days. Now that we already know we can use an array to store the temperatures, we can easily write the following code to store the temperatures over 2 days:
let averageTempDay1 = [72, 75, 79, 79, 81, 81]; let averageTempDay2 = [81, 79, 75, 75, 73, 72];
However, this is not the best approach; we can do better! We can use a matrix (a two-dimensional array or an array of arrays) to store this information, in which each row will represent the day, and each column will represent an hourly measurement of temperature, as follows:
let averageTemp = []; averageTemp[0] = [72, 75, 79, 79, 81, 81]; averageTemp[1] = [81, 79, 75, 75, 73, 73];
JavaScript only supports one-dimensional arrays; it does not support matrices. However, we can implement matrices or any multi-dimensional array using an array of arrays, as in the previous code. The same code can also be written as follows:
// day 1 averageTemp[0] = []; averageTemp[0][0] = 72; averageTemp[0][1] = 75; averageTemp[0][2] = 79; averageTemp[0][3] = 79; averageTemp[0][4] = 81; averageTemp[0][5] = 81; // day 2 averageTemp[1] = []; averageTemp[1][0] = 81; averageTemp[1][1] = 79; averageTemp[1][2] = 75; averageTemp[1][3] = 75; averageTemp[1][4] = 73; averageTemp[1][5] = 73;
In the previous code, we specified the value of each day and hour separately. We can also represent this two-dimensional array as the following diagram:

Each row represents a day, and each column represents the temperature for each hour of the day.