I have an array like this:
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
},
{
name: 'Redux',
exercises: 11,
id: 4
}
]
I would like to get the sum of the excercises. I'm trying to accomplish it thusly:
const Total = (props) => {
const total = props.parts.reduce( (prev, cur) => {
console.log('prev.excercises : ', prev.exercises)
console.log('cur.excercises : ', cur.exercises)
return prev.exercises + cur.exercises
})
return (
<>
<p>Number of exercises {total}</p>
</>
)
}
But this results in NaN. The console shows why this result occurs, but not why the prev.excercises value is acting weird:
prev.excercises : 10
cur.excercises : 7
prev.excercises : undefined
cur.excercises : 14
prev.excercises : undefined
cur.excercises : 11
I'm really new to js, so there is probably something really simple I'm doing wrong.. appreciate the help in advance!
reduce, thusprevwill change from being an object the first iteration to being a number the second one. Please review howArray#reduceworks because you're trying to do two conflicting things with it right now which would of course lead to weird results.reduce. You don't have an initial variable.prev.excercisesdoesn't exist.return prev.exercises + cur.exercisestoreturn prev + cur.exercises