0
const App = () => {
  const course = [{
    id: 1,
    name: 'Half Stack application development',
    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: 'Node.js',
    id: 2,
    parts: [
      {
        name: 'Routing',
        exercises: 3,
        id: 1
      },
      {
        name: 'Middlewares',
        exercises: 7,
        id: 2
      }
    ]
  }
]

I am trying to render a component which looks like this:

  • Half Stack application development Fundamentals of React: 10 Using props to pass data: 7 State of a component: 14 TOTAL EXERCISES: 31 Node.js Routing: 3 Middlewares: 7 TOTAL EXERCISES: 10

Using the following component:

const Course = ({course}) => {

return(
    <ul>
    {course.map(c => (
      <>
        <li>{c.name}</li>
        <ul>
          {c.parts.map(p =>
            <li>{p.name}: {p.exercises} {p.exercises.reduce((sum, item) => sum += item, 0))(</li>)}
        </ul>
        </>
    ))}
    </ul>
    
)

}

However, the component does not render as it says p.exercises.reduce is not a function.

How do I render the total amount of exercises after each part?

1
  • p.exercises is number not array. reduce is array method, you can't use it on type number. Commented Apr 28, 2022 at 14:05

1 Answer 1

2

You won't be able to reduce on a number (exercises is a number instead of an array), so you may have to change your render to something like this instead (if I'm understanding what you want to do correctly):

return(
    <ul>
    {course.map(c => (
      <>
        <li>{c.name}</li>
        <ul>
          {c.parts.map(p =>
            <li>{p.name}: {p.exercises} {c.parts.reduce((sum, item) => sum += item.exercises, 0))(</li>)}
        </ul>
        </>
    ))}
    </ul>
    
)

Let me know if this works!

Sign up to request clarification or add additional context in comments.

2 Comments

It works, thanks for your help. I was expecting a much simpler solution as this is supposed to be an exercise for total newbies, but I'm glad it works anyway.
Aw man, sorry to complicate things, but I'm glad it works. Good luck with the rest of your learning!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.