Skip to content

8.1.5 Manipulating 2d Arrays - Codehs

function sumBorder(matrix) 
  let sum = 0;
  let rows = matrix.length;
  let cols = matrix[0].length;

for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++) j === cols - 1) sum += matrix[i][j]; return sum;


"Write a function that rotates the 2D array 90 degrees clockwise." Codehs 8.1.5 Manipulating 2d Arrays

In the previous lessons, you learned how to create and access elements in 2D arrays (also known as matrices). In 8.1.5, you will go a step further: you will modify, traverse, and transform data inside 2D arrays. This is a critical skill for games (grids), data tables, image processing, and more.

A 2D array is essentially an array of arrays. function sumBorder(matrix) let sum = 0; let rows

let grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

int[][] matrix = 
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
;

To access an element in a 2D array, you need to specify its row and column index. The syntax for accessing an element is arrayName[rowIndex][columnIndex].

var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
var element = array[1][1]; // access element at row 1, column 1
console.log(element); // output: 5
function rotateClockwise(matrix) 
  let result = [];
  let rows = matrix.length;
  let cols = matrix[0].length;

for (let j = 0; j < cols; j++) let newRow = []; for (let i = rows - 1; i >= 0; i--) newRow.push(matrix[i][j]); result.push(newRow); return result; "Write a function that rotates the 2D array


Translate »