accordion file

Living in Two Dimensions (arrays that is)

I had mentioned in previous posts about looping and I have also discussed arrays before. Today I wanted to discuss two-dimensional arrays. Two-dimensional arrays allow you to house multiple pieces of information at multiple levels.

I like to think of arrays as accordion file folders. One item with multiple segments. A 2D array is like putting an accordion file folder inside another. Let’s see how these work…

As you can see from the aforementioned code, 2D arrays allow us to put several layers into one variable. Another way of thinking about it is that a 2D array is an array of an array.

You saw how I created it with the ‘new’ keyword, but there are other ways to create an array.

We could even initialize it on the fly…

Perhaps another way of thinking about a 2D array is like a table with columns and rows.

Now, anytime you have an array, chances are that you will need to loop over it. So how do we approach looping over a 2D array? Since we have two (2) dimensions, we will need two (2) loops. We have to nest them. Here is an example…

On a side note, we can add data to the end of an array by using the ‘push’ method…myArray.push(‘someValue’);

Happy Coding!

Clay Hess

Share this post