Comp 101 2D Arrays

What is a 2D Array?

A two-dimensional array is similar to any other array we've seen so far, but with one important difference, it's an array of arrays! Therefore, at each index of a 2D array, we have another array! This 'other array' will still have a fixed type (number, string, boolean, object, etc) which applies to every secondary array. 

An easy way to visualize this is as a grid system, where the row can be found by the index of the 1st array, and the column is the index of the second. 

How do we declare a 2D array?

Declaring a 2D array can be done in a very similar way to declaring a normal array, except instead of one set of brackets: [] , we have two: [][]

let wordsearch: string[][];

In the example above, we declared a two-dimensional string array array called wordsearch. If were were to access wordsearch[0] we would be accessing a string array instead of just an individual string. This string array would be or 0th row of our wordsearch 'grid.' If we wanted to access an individual element, we would also have to specify the column, which is the element's index in the secondary array. 

For example, say we wanted to access the string stored in the 0th row and 3rd column of our array, we would simply use the following:

let letter = wordsearch[0][3] // because we use row-column arrays, the row always comes in the first set of [], and the column in the 2nd

In a similar way, if we wanted to know how many strings there were in the second row of our 2D array, we could do this just like we'd find the length of a normal array:

let lengthrow = wordsearch[2].length;

More examples

Now that we're more comfortable with what we're working with, let's look at actually initializing a two-dimensional array. Say we want to create a representation of a game of tic-tac-toe.

let wordsearch: string[][] = [    
    ["x", "c", "o"],    
    ["o", "o", "h"],    
    ["k", "m", "j"],
    ["a", "p", "e"]
];

Looks like 1st column down spells comp! We did this by creating that "array of arrays" from earlier, with each entry in the array being an array of strings.

(Although in the real world, 2D arrays can be "jagged," or of varying sizes, you can always expect that the 2D arrays you see will have the same number of "columns". For instance, you'll never have two rows with different sizes.)