Menu
Coddy logo textTech

Accessing 2D Array Elements

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 7 of 65.

Accessing elements in a 2D array is similar to accessing elements in a 1D array, but instead of using a single index, you use two indices: one for the row and one for the column. For instance:

const seats = [
  ['A1', 'A2', 'A3'],
  ['B1', 'B2', 'B3']
];
// seats[0][2] -> 'A3'
// seats[1][1] -> 'B2'

Remember that indices in JavaScript start a 0, so the first row is at index 0, the second row is at index 1, and so on.

challenge icon

Challenge

Easy

Create a function named getColumn that takes three arguments: a 2D array matrix, an integer numberOfRows, and an integer colIndex. The function should return an array containing all elements in the specified column colIndex

Cheat sheet

Access elements in a 2D array using two indices: [row][column]

const seats = [
  ['A1', 'A2', 'A3'],
  ['B1', 'B2', 'B3']
];
// seats[0][2] -> 'A3'
// seats[1][1] -> 'B2'

Indices start at 0 for both rows and columns.

Try it yourself

function getColumn(matrix, numberOfRows, colIndex) {
  // TODO: Return an array containing elements from the specified column index
}
// Do not write anything outside function
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow