JavaScript Program to Find Sum of elements in a Matrix
Last Updated :
05 Oct, 2023
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) => {
let sum = 0;
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
return sum;
}
const matrix = [
[12, 14, 13],
[18, 15, 16],
[17, 11, 19],
];
const result = sumMatrix(matrix);
console.log(result);
|
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);
|
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) => {
let sum = 0;
mat.forEach((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);
|
Share your thoughts in the comments
Please Login to comment...