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!
CodePudding user response:
You're trying to access it as an object but are returning it as an integer
const Total = (props) => {
const total = props.parts.reduce( (prev, cur) => {
console.log('prev.excercises : ', prev.exercises)
console.log('cur.excercises : ', cur.exercises)
return {exercises : prev.exercises cur.exercises}
})
If you don't want to return object you can do it like this
const total = props.parts.reduce( (prev, cur) => {
prev=typeof prev==="object" ? prev.exercises:prev
console.log('prev.excercises : ', prev)
console.log('cur.excercises : ', cur.exercises)
return prev cur.exercises })
CodePudding user response:
In the below code when the first time you call prev it is an object, but as you only return the value of sum of exercises in the next iteration, it can't find a property of exercise since it is an int and not an object.
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>
</>
)
}
So try the following code
const Total = (props) => {
const total = props.parts.reduce( (prev, cur) => {
console.log('prev.excercises : ', prev.exercises)
console.log('cur.excercises : ', cur.exercises)
return {exercises : prev.exercises cur.exercises}
})
return (
<>
<p>Number of exercises {total.exercises}</p>
</>
)
}
return the value as an object so the property of exercises could be found after 1st iteration. you will get an object {exercises:value} object as total and render the value by calling total.exercises.