0

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

Pabblo96
  • 49
  • 5
  • create an integer variable and increase it by the expense amount in the loop – Luca Kiebel Feb 22 '22 at 17:41
  • 1
    `expenseList.reduce((acc, array) => +array[2] + acc, 0);` if expenseList is an array. If expenseList is an object, do that to `Object.values(expenseList)` – danh Feb 22 '22 at 17:48
  • Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Ismael Vacco Feb 23 '22 at 23:49

1 Answers1

1

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)
Cohars
  • 3,822
  • 1
  • 29
  • 50