JavaScript Tip: Nested Arrays

Sometimes, you’ll need to store an array within an array. Sometimes, you’ll require even more nesting.

Note: although it’s possible to nest a number of arrays, I’d advise against it, as working with many array indices can be confusing to work with.

Let’s start with two simple arrays, which we’ll call them x and y. We’ll fill x with some values:

Now, reading any of the values from the y array is as simple as passing in an index, which means placing the index value between a set of square brackets placed next to the array name. So, if I wanted “cobb”, I’d pass in an index of 0:

But what if dreamers wasn’t a named array but merely defined inline:

How would we now get to “cobb”? By using: x[0][0].

In the first square  brackets, you define the index of the first array you want to read from; in the second  set, you define the second index. So, reading “arthur” would be x[0][1],  “ariadne” would be x[0][2], and so on.

Leave a Reply

Your email address will not be published. Required fields are marked *