I know the question is how to use reduce
(and another answer already explained how to do it), but in fact you don’t need it. A loop simple already solves:
let total = 0;
for (const fruit of fruits) {
total += fruit.price;
}
// usar o total do jeito que quiser
Or the for
more traditional:
let total = 0;
for (let i = 0; i < fruits.length; i++) {
total += fruits[i].price;
}
That’s all.
"Ah, but I want use reduce
."
What for? Do you really need it? Unless they’re "forcing" you, I don’t see any technical or practical reason to use it instead of a loop simple (except perhaps for personal taste, or "good practice", or "functional paradigm is cooler", etc). Perhaps you are told that it is "better because it has fewer lines":
let total = fruits.reduce((a, b) => a + b.price, 0);
But "smaller code" is not necessarily "better". Not least because reduce
generally will be slower than a for
simple (of course for a few small arrays, the difference will be insignificant and imperceptible, but increase their size and the difference becomes evident).
Just to make it clear that I am not against the use of reduce
in itself. I just think it’s "overvalued", and it’s not always necessary (to sum up elements of an array, I definitely find it an exaggeration).