In JavaScript, you can store multiple values in a single variable by creating an array. Each value, called an “item” or “data item,” gets a unique number, called an “index,” that represents when it was stored in the array relative to the others.
Sometimes, though, you need to make things a little more sophisticated than an ordinary list. You need a list with two or more dimensions. And when that’s the case, you’ll need to create a two-dimensional (or three-, or multi-dimensional) array. This tutorial will show you how.
How to Create and Reference Multi-Dimensional Arrays
Suppose you want to make a shopping list for your groceries. The list has apples, bananas, and oranges. You can make that list by storing these foods in an array-type object:
list = ['apples', 'bananas', 'oranges']
Whenever you need to remember what foods you added to your grocery shopping list, you can reference the array or the individual items on it:
console.log(list) // Logs ['apples', 'bananas', 'oranges']
console.log(list[0]) // Logs apples
console.log(list[1]) // Logs bananas
console.log(list[2]) // Logs oranges
But what if you want to remember the quantity that you want to buy for each food? That’s where multi-dimensional arrays come into play. To achieve this, you can add a second dimension to your array by nesting each item within an array of its own:
list = [['apples', 4], ['bananas', 2], ['oranges', 8]]
See what we did there?
Now, you know that you need to buy 4 apples, 2 bananas, and 8 oranges. If you ever forget and you need to refresh your memory of this, you can reference the items and nested items in your array like this:
console.log(list) // Logs [['apples', 4], ['bananas', 2], ['oranges', 8]]
console.log(list[0]) // Logs ['apples', 4]
console.log(list[0][0]) // Logs apples
console.log(list[0][1]) // Logs 4
console.log(list[1]) // Logs ['bananas', 2]
console.log(list[1][0]) // Logs bananas
console.log(list[1][1]) // Logs 2
console.log(list[2]) // Logs ['oranges', 8]
console.log(list[2][0]) // Logs oranges
console.log(list[2][1]) // Logs 8
And that’s how you create a two-dimensional array and reference the items in it!
Remember that this technique is for multi-dimensional arrays as a whole. Which means you can add a third dimension to turn your two-dimensional array into a three-dimensional array, a fourth, a fifth, and so on as your application grows. Just keep things as simple as you can so they don’t need too much computing power and remain performant.
In Summary
Creating a two-dimensional (or a multi-dimensional) array is not that different from creating a single-dimensional array. You declare the array in the same way, but to add dimensions, you nest arrays within your array.
You can then expand horizontally, by adding items to your nested arrays, or vertically, by nesting more arrays within the nested arrays.