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