Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Render the sum of multiple arrays in a single react component

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading