Codehs 8.1.5 Manipulating 2d Arrays __full__ Jun 2026
When assigning a new value, remember that you are writing directly back to the grid coordinates: array[r][c] = newValue; Use code with caution. Common Challenges and How to Fix Them Challenge 1: ArrayIndexOutOfBoundsException
function zeroOutNegatives(matrix) for (let i = 0; i < matrix.length; i++) for (let j = 0; j < matrix[i].length; j++) if (matrix[i][j] < 0) matrix[i][j] = 0;
Performing mathematical operations on every element, like doubling every value in the array.
In Java (the language typically used on CodeHS), you can visualize a 2D array like this: Codehs 8.1.5 Manipulating 2d Arrays
When you declare a 2D array, you specify the number of rows and columns: int[][] matrix = new int[3][4]; // 3 rows, 4 columns Use code with caution. This creates a grid that looks like this: Row 1 Row 2
Inside the inner loop, perform the action. If the exercise asks you to make all numbers negative, you would do: grid[r][c] = -Math.abs(grid[r][c]); 4. Return or Print the Result
var grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; // add a new button to the grid grid.push([10, 11, 12]); // remove a button from the grid grid.splice(1, 1); console.log(grid); // output: [[1, 2, 3], [7, 8, 9], [10, 11, 12]] When assigning a new value, remember that you
To remove a row from a 2D array, you can use the splice() method.
var myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; myArray.push([10, 11, 12]); // myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]];
function incrementAll(matrix) for (let i = 0; i < matrix.length; i++) for (let j = 0; j < matrix[i].length; j++) matrix[i][j]++; This creates a grid that looks like this:
This function systematically checks each element and stops as soon as it finds a match. This pattern is useful for everything from locating a "Waldo" in a grid to validating user input.
for (int row = 0; row < array.length; row++) for (int col = 0; col < array[0].length; col++) // Manipulate array[row][col] here Use code with caution. Controls the rows ( array.length ). Inner Loop: Controls the columns ( array[0].length ). Common Manipulation Patterns in 8.1.5
A 2D array is essentially an array of arrays. When you declare int[][] matrix = new int[3][4] , you are creating a structure with 3 rows and 4 columns. To manipulate this data effectively, you must master the relationship between the outer loop (rows) and the inner loop (columns).