Open In App

JavaScript Program to Find Sum of elements in a Matrix

Last Updated : 19 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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

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.

Syntax:

for ( variable of iterableObjectName) {
...
};

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

JavaScript
const sumMatrix = (matrix) => {

    // Initialise the local sum variablle to store sum
    let sum = 0;

    // Iterate through each row in a matrix
    for (let i = 0; i < matrix.length; i++) {
        //iterate through each element of row
        for (let j = 0; j < matrix[i].length; j++) {
            //compute the sum
            sum += matrix[i][j];
        }
    }
    return sum;
}

const matrix = [
    [12, 14, 13],
    [18, 15, 16],
    [17, 11, 19],
];

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

Output
135

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.

Syntax:

array.reduce( function(total, currentValue, currentIndex, arr), 
initialValue )

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

JavaScript
const sumOfMatrix = (mat) => {
    return mat.reduce((acc, row) => {
        return acc + row.reduce((sum, cell) => sum + cell, 0);
    }, 0);
}

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

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

Output
45

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.

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

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.

Step 1: Flatten the Matrix: Convert the 2D matrix into a 1D array using flatMap().

Step 2: Compute the Sum: Apply reduce() method on the flattened array to compute the sum.

JavaScript
const sumMatrix = (matrix) => {
    // Flatten the matrix and compute the sum using flatMap() and reduce()
    return matrix.flatMap(row => row).reduce((acc, curr) => acc + curr, 0);
}

// Test matrix
const matrix = [
    [12, 14, 13],
    [18, 15, 16],
    [17, 11, 19],
];

const result = sumMatrix(matrix);
console.log(result); // Output: 135

Output
135

Approach 5: Using JavaScript Array.flat() Method

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. By using flat(), we can flatten the matrix to a single-dimensional array and then use the reduce() method to compute the sum of all elements.

Example: In this example, we use the flat() method to flatten the matrix into a 1D array and then sum all its elements using the reduce() method.

JavaScript
const sumMatrix = (matrix) => {
    // Flatten the matrix to a single-dimensional array and compute the sum
    return matrix.flat().reduce((acc, curr) => acc + curr, 0);
}

// Test matrix
const matrix = [
    [5, 10, 15],
    [20, 25, 30],
    [35, 40, 45],
];

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

Output
225

Next Article

Similar Reads