I'm using Javascript, and I have an array like this:
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 10 },
{ id: 3, value: 5 },
{ id: 4, value: 3 }
]
I want to get a variable total, with the sum of every value field in the counters array. Right now I'm doing:
Total() {
let total = 0;
for (let i = 0; i < counters.length; i++) {
total += counters[i].value;
}
return total;
}
Even if that works, I know that there's a better way. I tried reduce
method, but I couldn't get what I need. How can I do it?