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…
var myArray = new Array(2); // Creates an array with two sections myArray[0] = new Array(); // Creates an empty array and inserts it into the first slot of the top-most array myArray[0][0] = "I am the value of myArray[0][0]"; // Inserts a string into the inner array myArray[1] = "I am the value of myArray[1]"; // Inserts a string in the second index of the top-most array
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.
var myArray = new Array(new Array(3), new Array(6), new Array(9));
We could even initialize it on the fly…
// Single array var myArray = ['firstvalue','secondvalue']; // 2D array var myArray = [['firstvalue1d','secondvalue1d'],['firstvalue2d','secondvalue2d']];
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…
for(var i=0; i < outerArray.length; i++){ // loops over outer array for(var j=0; j < outerArray[i].length; j++){ // loops over inner array // output array data console.log(outerArray[i][j]); } }
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