Comp 110 2D Arrays

2D Arrays

A 2D array is just an "array of arrays." We can essentially think of this as being a 2D grid, with each element in the grid being of the same type. The general syntax for declaring a 2D array is:

let <name>: <type>[][];
 
// example usage:
let dictionary: string[][];

When creating a 2D array we also need to consider how we will be accessing elements. A column-major 2D array means that the columns array is the outer most array. Similarly, row-major means that the rows array is the outer array. In this class, you can assume all 2D arrays you are working with are row-major. For example, if you wanted to access the 3rd item in the 1st row, you would do:

let x = randomArray[1][3];

We use the index of the row first and then the index of the column. Keep in mind that when we are working with arrays, the indices are off by one since we start at 0. So in this case, the element at randomArray[1][3] is actually in the second row & fourth column when looking at the grid visually.

Assigning to inner array:

<name>[rowIndex][columnIndex] = <value>;
 
// Example
let arr: number[][] = [  
                         [1, 2, 3],
                         [4, 5, 6],
                         [7, 8, 9] 
];
randomArray[2][2] = 100;
// This will put replace 9 with 100 in the 2nd row, 2nd column of the array

Accessing element of inner array:

<name>[rowIndex][columnIndex];
  
// Example
let arr: number[][] = [  
                         [1, 2, 3],
                         [4, 5, 6],
                         [7, 8, 9] 
];
print(randomArray[2][2]);
// This will print 9, the element in the 2nd row and 2nd column of the array.

Getting # of elements of inner array:

<name>.[rowIndex].length;
 
// Example
let a: number[][] = [
                        [1, 2, 3, 4],
                        [5, 6, 7, 8]
];
print(a[0].length);
// This will print 4, the length of the 0th row. The length of each row is equal to the number of columns!

Assigning to outer array:

<name>[rowIndex] = <array of correct type>;
 
// Example
let arr: number[][] = [  
                         [1, 2, 3],
                         [4, 5, 6],
                         [7, 8, 9] 
];
randomArray[2] = [1, 2, 3];
// This will reassign the 2nd row of the array to be [1, 2, 3]

Accessing element of outer array:

<name>[rowIndex];
 
// Example:
let arr: number[][] = [  
                         [1, 2, 3],
                         [4, 5, 6],
                         [7, 8, 9] 
];
let y: number[] = arr[2];
print(y);
// [7, 8, 9] will be printed

Getting number of elements of outer array:

<name>.length;
 
// Example:
let a: number[][] = [    
                        [1, 2, 3, 4],
                        [5, 6, 7, 8]
];
print(a.length)
// 2 will be output to the screen. This is the number of rows in our 2D array.

Note that all of these examples were written using row-major conventions!