Home > Enterprise >  Render the sum of multiple arrays in a single react component
Render the sum of multiple arrays in a single react component

Time:04-29

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?

CodePudding user response:

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!

  • Related