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.
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.