Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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]]

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

const array = [[4, 5, 6], [6, 5, 4], [5, 5, 5]]
const result = array.map(subArr => {
return subArr.reduce((pre, item) => pre + item, 0)
})
console.log(result)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!