Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
Access the sum of multiple arrays in React
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 calculate the sum of the exercises in each of the courses so I can get something at the end of each course which says Total exercises: 31 at the end of Half Stack Application Development and total exercises 10: at the end of Node.Js

I have tried

const totals = course.map(c => c.parts.map(c => c.exercises.map(c => c.reduce((a, b) => a + b, 0))))

but received c.exercises.map is not a function.

How could I calculate the sum of each of c.exercises?

exercises looks like this in the console:

(2) [Array(3), Array(2)]
0: (3) [10, 7, 14]
1: (2) [3, 7]
length: 2
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This to calculate just the number of exercises per course

const calculateTotalExercises = course =>
  course.map(c => c.parts.reduce((res, {
    exercises
  }) => res + exercises, 0))

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

console.log(calculateTotalExercises(course))

Probably it will be more convenient to add the total of the exercise to the array like this

const calculateTotalExercises = course =>
  course.map(c => ({...c, totalExercise : c.parts.reduce((res, p) => res + p.exercises, 0)}))

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

console.log(calculateTotalExercises(course))

about 4 years ago · Juan Pablo Isaza Relatório

0

You could start by breaking the problem down. Here's how I solved this.

I created a function that finds the total number of exercises for one course

let totalExerciseForOneCourse = (parts) => {
  return parts.reduce((prev, curr) => prev + curr.exercises, 0)
}

Then we use the map method to go through each course in the courses array returning a new array of objects with everything that was in the courses array and adding in a totalExercises object property

let newCourses = courses.map((course) => {
  const total = totalExerciseForOneCourse(course.parts);
  return Object.assign({}, course, {
    totalExercises: total
  })
})

Our totalExerciseForOneCourse function takes an array parameter and calculates the sum of all exercises for one course using the array.reduce method

newCourses contains our new array with all previous and new information

JSFiddle -

https://jsfiddle.net/swish933/9fwzysxa/

about 4 years ago · Juan Pablo Isaza Relatório

0

The sum of multiple arrays can be rendered in a single component looking like this

{c.parts.reduce((a, b) => a += b.exercises, 0)}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda