Codehs 8.1.5 Manipulating 2d Arrays 💯 Premium
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
// Sum of a specific row int rowSum = 0; for (int col = 0; col < matrix[rowIndex].length; col++) rowSum += matrix[rowIndex][col];
// Sum of a specific column int colSum = 0; for (int row = 0; row < matrix.length; row++) colSum += matrix[row][colIndex];
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++) return sum;
"Write a function that rotates the 2D array 90 degrees clockwise."
Q: Does 8.1.5 expect me to return a new array or modify the original?
A: Read the prompt carefully. 90% of the time, the phrase "modify the given array" means change the original in place (void method). If it says "return a new array", then do not modify the original. Codehs 8.1.5 Manipulating 2d Arrays
Q: My code works manually but fails the test cases. Why?
A: The test cases may use a different matrix size (e.g., 2x5 instead of 4x4). Ensure you don't hardcode numbers like 3 or 4. Use .length.
Q: How do I handle ragged 2D arrays (different column lengths per row)?
A: Use arr[i].length for each row in the inner loop. Avoid arr[0].length if rows have different sizes. To access an element in a 2D array,
// Double every element
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
matrix[row][col] *= 2;
Depending on your specific school’s sandbox, 8.1.5 may ask you to implement one or more of the following methods.
int sum = 0;
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
sum += matrix[row][col];