How to useJavaScript forEach Method in Javascript

ForEach will be called twice in this approach. Inside an outer forEach, an inner forEach iterates through each row of a matrix, then. The sum is determined by adding each element to the variable we have.

Syntax:

array.forEach(callback(element, index, arr), thisValue)

Example: In this example we are using the above-explained approach.

Javascript
const sumMatrix = (mat) => {

    // Local variable sum to accumulate sum
    let sum = 0;

    // Outer foreach loop iterates over 
    // each row in the matrix
    mat.forEach((row) => {
        // Inner foreach loop iterates over 
        // each element (cell) in that row.
        row.forEach((cell) => {
            sum += cell;
        });
    });
    return sum;
}

const matrix = [
    [11, 2, 3],
    [4, 15, 6],
    [7, 8, 19]
];

const result = sumMatrix(matrix);
console.log(result);

Output
75

JavaScript Program to Find Sum of elements in a Matrix

In this article, we are going to learn about finding the Sum of elements in a Matrix by using JavaScript. The sum of elements in a matrix refers to the result obtained by adding all the individual values within the matrix, typically represented as a two-dimensional grid of numbers or elements.

Examples:

Input: [1, 2, 3],
[4, 5, 6],
[7, 8, 9]
Output: Sum = 45
Explanation: if we do sum of all element of matrix using computation 1+2+3+4+5+6+7+8+9 equals to 45

Table of Content

  • Approach 1: Using JavaScript for Loop
  • Approach 2: Using JavaScript Array.reduce() Method
  • Approach 3: Using JavaScript forEach Method
  • Approach 4: Using JavaScript flatMap() Method

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using JavaScript for Loop

A for loop iterates through each row and column of the matrix, accumulating the sum of elements. It’s a basic yet effective method for matrix summation in JavaScript....

Approach 2: Using JavaScript Array.reduce() Method

In this approach we will use the reduce() method two times. Row by row, the outer reduce method totals the sum. Row by row, an inner reduce method adds up the elements. As the second argument, the 0 passes and the accumulator is initialized....

Approach 3: Using JavaScript forEach Method

ForEach will be called twice in this approach. Inside an outer forEach, an inner forEach iterates through each row of a matrix, then. The sum is determined by adding each element to the variable we have....

Approach 4: Using JavaScript flatMap() Method

The flatMap() method is used to flatten the matrix and then compute the sum of all elements in a concise manner....