I have been always using for to calculate any sum in a table, but I heard that there is a proper way, it is by using reduce, I followed the documentation and few examples using simple arrays, but I am using an array of objects, and here is my simple code, because I know I am missing something simple :
let dataRevenus = [
{ id: 1, label: intl.get("REVENUES_FONCIERS"), value: 230000000 },
{ id: 2, label: intl.get("REVENUES_VALUERS_MOBILIERES"), value: 25000000 },
{ id: 3, label: intl.get("PENSIONS_RETRAITES"), value: 33008.0 }
];
let test = 0;
let sum = dataRevenus
? dataRevenus.reduce((acc, item) => {
console.log("here : " + parseFloat(item.value));
test = test + parseFloat(item.value);
return test;
})
: 0;
console.log(sum);
What I see in my console is that the first item has not been taken in consideration, this is what I get as a result :
here : 25000000
here : 33008
25033008
It seems like I am calcumating the sum correctly but the value of thje first item is not calculated
Any help would be much apppreciated
parseFloat(item.value)it's already a number, you don't need to parse it.reducewill take the first element asaccand thus it "skips" it because you don't get to process it asitem. Another problem is that you aren't usingaccbut an outside variable. That works but it's not howreduceis supposed to run.