Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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  })
about 4 years ago · Juan Pablo Isaza Report

0

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
  })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!