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

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

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 :

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