Start learning free

LESSON 254 OF 671 · NESTED LOOPS OVER GRIDS

Grid Sum in JavaScript: Nested for...of Loops

Practice Read the full explanation

Given a grid of integers grid, return the sum of all the numbers in it.

A grid is a table of numbers made of rows. Every row has the same number of values, one in each column. Rows are counted from the top and columns from the left, both starting at 0.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: 21
Explanation: The first row adds up to 1 + 2 + 3 = 6 and the second to 4 + 5 + 6 = 15. Together: 6 + 15 = 21.

Example 2:

Input: grid = [[-3, 4],
               [5, -6]]
Output: 0
Explanation: -3 + 4 + 5 + (-6) = 0. Negative numbers make the sum smaller.

Example 3:

Input: grid = [[7]]
Output: 7
Explanation: A grid with one row and one column holds a single number.

 

Constraints:

  • grid has at least 1 row and at most 10 rows.
  • Every row has the same number of values, at least 1 and at most 10.
  • Every value is an integer between -1000 and 1000.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · NESTED LOOPS OVER GRIDS

    Grid Sum in JavaScript, explained

    Problem overview

    The method gridSum(grid) receives a grid of integers and returns the sum of every number in it. In JavaScript a grid is an array of rows, and each row is an array of numbers. Rows are counted from the top and columns from the left, both from 0. Every row has the same number of values.

    For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6 and the second to 15, so the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, because negative numbers make the sum smaller. For [[7]] the grid has one cell, and the answer is 7.

    Approach

    Adding up an ordinary array takes one loop: visit each value and add it to a running total. A grid is an array whose items are themselves arrays, so one loop is not enough. The outer loop visits the rows, and for each row an inner loop visits that row's values. Together the two loops reach every cell exactly once, and every cell is added to the same total.

    The order of the cells doesn't matter for a sum, so the answer comes out the same whether you walk the grid by rows or by columns. Walking by rows is the natural way, because a row is what the outer array hands you.

    Step by step

    1. Create total with let and start it at 0. It holds the sum of the numbers added so far, and no number has been added yet.
    2. Loop over the rows. for (let row of grid) gives one row per turn, from the top row to the bottom one. Each row is an array of integers.
    3. Loop over the values of the row. Inside the outer loop, for (let value of row) visits every value of the current row before the outer loop moves on.
    4. Add the value. total += value is short for total = total + value. Negative values are added like any others, so they lower the total.
    5. Return total after both loops. A return inside a loop would end the function after the first row or the first value.

    The solution in JavaScript

    class Solution {
        gridSum(grid) {
            let total = 0;
            for (let row of grid) {
                for (let value of row) {
                    total += value;
                }
            }
            return total;
        }
    }
    

    Details worth knowing:

    • for...of gives values, not positions. This lesson never needs the row or column number, which is why for...of is enough. When a position matters, as in finding a cell, you need an index loop instead.
    • let for the total, and for the loop variables. total is reassigned on every addition, so it can't be const. The loop variables row and value are new bindings on every turn, and const would also work for them.
    • A row is an array. row in the outer loop is the whole array, for example [1, 2, 3], not a number. Adding it directly to the total would turn the total into a string.

    Complexity

    Time: O(r × c) for r rows and c columns, which is the number of cells. Each cell is visited once and added in constant time.

    Space: O(1). The function keeps one number and the loop variables, however large the grid is.

    Edge cases and common mistakes

    • A single cell. [[7]] makes each loop run once and returns 7.
    • Negative numbers. [[-3, 4], [5, -6]] gives 0. Nothing special is needed, but a total that started at a large number instead of 0 would break such cases.
    • Resetting the total. The total belongs outside both loops. If let total = 0 were inside the outer loop, each row would start over and the function would return only the last row's sum.
    • Returning too early. Put return total after both loops close.
    • Looping over the grid once. for (let value of grid) gives rows, not numbers. Adding an array to a number produces a string: for [[1, 2, 3], [4, 5, 6]] the "total" ends as "01,2,34,5,6", not a sum.

    Testing

    • grid = [[1, 2, 3], [4, 5, 6]] gives 21.
    • grid = [[-3, 4], [5, -6]] gives 0.
    • grid = [[7]] gives 7.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free