w3resource

JavaScript: Sum of all odds in a matrix

JavaScript Math: Exercise-91 with Solution

Write a JavaScript program to calculate the sum of all odd elements in a square matrix.

Test Data:
([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) -> 25
( [ [-1, -2], [-4, -5] ]) -> -6

Sample Solution:

JavaScript Code:

/**
 * Function to calculate the sum of all odd numbers in a matrix.
 * @param {number[][]} nums - The matrix containing numbers.
 * @returns {number} - The sum of all odd numbers in the matrix.
 */
function test(nums) {
    // Flatten the matrix into a single array
    return nums.reduce((b,a) => [...b,...a], [])
        // Calculate the sum of all odd numbers in the flattened array
        .reduce((b,a) => !(a%2) ? b: a+b , 0);
}

// Test cases
// Test the sum of all odd numbers in the first matrix
nums = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
       ];
console.log("Sum of all odds of the said matrix: "+test(nums));

// Test the sum of all odd numbers in the second matrix
nums = [
        [-1, -2],
        [-4, -5]
       ];
console.log("Sum of all odds of the said matrix: "+test(nums));

Output:

Sum of all odds of the said matrix: 25
Sum of all odds of the said matrix: -6

Flowchart:

JavaScript: Sum of all odds in a matrix.

Live Demo:

See the Pen javascript-math-exercise-91 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Test if a number is a Harshad Number or not.
Next: Iterated Cube Root.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-math-exercise-91.php