HomeAbout

2D Arrays

Traversal

Brute force looping:

for(let i=0; i<array.length; i++) { for(let j=0; j<array[i].length; j++) { console.log(array[i][j]); } }

Length

const array = [ [1,2,3], [4,5,6], [7,8,9], ]; let numRows = array.length; let numCols = array[0].length;

Modifying

Adding a new row at the end:

const array = [ [1,2,3], [4,5,6], [7,8,9], ]; // adding fourth row array[3] = [10,11,12];

Removing a column:

const array = [ [1,2,3], [4,5,6], [7,8,9], ]; // removing second column for(let i=0; i<array.length; i++){ // splice(start_at_index, el_count) array[i].splice(1,1); // remove 1 element (col) at index 1 of each row } // result [1,3] [4,6] [7,9]

Remove a row:

const array = [ [1,2,3], [4,5,6], [7,8,9], ]; // remove a second row array.splice(1,1); // remove 1 element (row) at index 1 // result [1,2,3] [7,8,9]

Control Flow

break for exiting loop as whole.

  • moves to outer scope/loop.

continue to skip current iteration.

  • moves to i++ of current loop.
AboutContact