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

186
Views
Sum objects from array in JavaScript (JS)

I want to sum expense but i dont know how, can somebody explain

for (let i = 0; i < ExpensesList.length; i++) {
    const expense = Number(ExpensesList[i][2])
    console.log(expense);
}

ExpenseList:

0: ["First expense", "2022-02-05", "51"]
1: ["Second expense", "2022-02-05", "5"] 
2: ["Third expense", "2022-02-12", "213"]

In console.log i have 51, 5, 213 sum of this is 269 but i dont know how to add that to each other

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

0

You need to declare a variable (let's call it sum) outside of the loop and increment it for each item in within the loop.

You could log it in the loop to see it being increased for each item, but what you want is to use it after the loop.

const expensesList = [
  ["First expense", "2022-02-05", "51"],
  ["Second expense", "2022-02-12", "213"]
]

let sum = 0
for (let i = 0; i < expensesList.length; i++) {
    sum += Number(expensesList[i][2])
}

console.log(sum)

Btw I also renammed the variable expensesList.

Here is another solution with [].reduce and some destructuring:

const sum = expensesList.reduce((result, [,,e]) => result + Number(e), 0)
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!