Book Image

Learning JavaScript Data Structures and Algorithms

By : Loiane Avancini
Book Image

Learning JavaScript Data Structures and Algorithms

By: Loiane Avancini

Overview of this book

Table of Contents (18 chapters)

Two-dimensional and multi-dimensional arrays


At the beginning of this chapter, we used the 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 that we can use an array to store the temperatures, we can easily write the following code to store the temperatures over two days:

var averageTempDay1 = [72,75,79,79,81,81];
var averageTempDay2 = [81,79,75,75,73,72];

However, this is not the best approach; we can write better code! We can use a matrix (two-dimensional array) to store this information, where each row will represent the day and each column will represent every hourly measurement of the temperature:

var averageTemp = [];
averageTemp[0] = [72,75,79,79,81,81];
averageTemp[1] = [81,79,75,75,73,72];

JavaScript only supports one-dimensional arrays; it does not support matrices. However, we can implement matrices or any multidimensional array by using an array of arrays...