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
EasyCreate 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 functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys