Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get sum of each row elements in an array of arrays JS

I am trying to find the sum of each row of an array of arrays in JavaScript. My first attempt:

const rowSums = [];
for (let row = 0; row < matrix.length; row++) {
    let currentRowSum = 0;
    for (let col = 0; col < matrix[row].length; col++) {
        currentRowSum += matrix[row][col];
    }
    rowSums.push(currentRowSum);
}

Now I am trying to find the sums using the reduce() method. I don’t see why this code doesn’t work:

const rowSums = matrix.reduce((rowSums, currentRow) => {
        return rowSums.push(currentRow.reduce((sum, currentEl) => {
            return sum + currentEl;
        }, 0))
}, []);

You can use this input for reference:
[[4, 5, 6], [6, 5, 4], [5, 5, 5]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It does not work because .push(...) returns the new length of the array instead of the array itself.

Push modifiers the array in place, so in your case you have to then return the same array with return rowSums.

const matrix = [[4, 5, 6], [6, 5, 4], [5, 5, 5]]

const rowSums = matrix.reduce((rowSums, currentRow) => {
    rowSums.push(currentRow.reduce((sum, currentEl) => {
        return sum + currentEl;
    }, 0))
    return rowSums;
}, []);

console.log(rowSums)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading