mortar-1
mortar-1

Reputation: 137

javascript reduce on properties of an array of objects acting weird

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!

Upvotes: 0

Views: 66

Answers (2)

mortar-1
mortar-1

Reputation: 137

I also got it working like this, but I guess Ahmed Ali's answer is more to the nose!

const Total = (props) => {

  const total = props.parts.map(part => part.exercises).
  reduce((prev, cur) => {
    console.log('prev : ', prev)
    console.log('cur : ', cur)
    return prev + cur
  })

Upvotes: 0

Ahmed Ali
Ahmed Ali

Reputation: 537

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  })

Upvotes: 2

Related Questions