Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
Iterate through an array of objects and calculate one single property value

So let's say we do have this array:

const db = [
{name: 'Coffe', price: '10'},
{name: 'Stackoverflow Stickers', price: '7.5'},
{name: 'Nike Air Force', price: '100'},
// more objects in similar format (long list)
]

So what I want to do is iterate through array and calculate all prices of each object value, in this case price.

What I tried, but somehow it doesn't work works:

let total = 0;
data.map((d) => (d.total += total))
setTotal(totalValues)
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use the Array.reduce function:

const total = db.reduce(
  (total, curr) => total + parseFloat(curr.price),
  0
);
setTotal(total);

Read more: https://www.w3schools.com/jsref/jsref_reduce.asp

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can use array reduce for this

don't forget to parseFloat your string in db data

const db = [
{name: 'Coffe', price: '10'},
{name: 'Stackoverflow Stickers', price: '7.5'},
{name: 'Nike Air Force', price: '100'},
]

let total = db.reduce((previous, current) => (previous + parseFloat(current.price)), 0)
console.log(total)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try the below changes to fix the issue. Inside map function instead of (d) => (d.total += total) use (d) => (total+= Number(d.price)).

const data = [
{name: 'Coffe', price: '10'},
{name: 'Stackoverflow Stickers', price: '7.5'},
{name: 'Nike Air Force', price: '100'},
// more objects in similar format (long list)
]

let total = 0;
data.map((d) => (total+= Number(d.price)))
console.log(total)

Note: Instead of using map , use forEach or a normal loop for these kind of operations. Like this:

data.forEach((d) => (total+= Number(d.price)))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda