Thus:
array.reduce((a, b) => a + b.points, 0)
Basically, what happens is that the function you pass by parameter to the reduce
(a + b.points
) will be executed for each item of the array.
The parameter a
will receive the value of the last call result (if it is the first call it will receive the value of the second function parameter reduce
- that 0).
The parameter b
will receive every item from array.
Something like that:
1. Item do Array
a = 0
b = { name: 'Batata', points: 23 }
Retorno da função: 0 + 23
2. Item do array
a = 23
b = { name: 'Pizza', points: 50 }
Retorno da função: 23 + 50
3º Item do array
a = 73
b = { name: 'Tacos', points: 60 }
Retorno da função: 73 + 60
The function that you
See working:
var array = [
{
name: 'Batata',
points: 23,
},
{
name: 'Pizza',
points: 50,
},
{
name: 'Tacos',
points: 60,
},
];
var soma = array.reduce((a, b) => a + b.points, 0)
console.log(soma)