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

170
Vistas
How can I sum object values by array data using ES standard?

I have an array of objects. Each object has a "tag" property with an array list. The values in this list repeat from object to object. I would like to sum up "cost" and "revenue" based on the "tag" arrays. Not sure explanation makes sense but I have the data structure below.

What I want the data to look like:

const expected = 
  [ { cost:  500, revenue:  800, tag: 'new'       } 
  , { cost:  800, revenue: 1400, tag: 'equipment' } 
  , { cost: 1300, revenue: 1650, tag: 'wholesale' } 
  , { cost:  300, revenue:  600, tag: 'old'       } 
  ] 

what the data looks like:

const data = 
  [ { cost: 500, revenue: 800, tag: [ 'new', 'equipment', 'wholesale' ]} 
  , { cost: 300, revenue: 600, tag: [ 'old', 'equipment'              ]} 
  , { cost: 800, revenue: 850, tag: [ 'wholesale'                     ]} 
  ] 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

A reduce and forEach to group by tag and then taking the values for each tag

var a= [
  {
    "cost": 500,
    "revenue": 800,
    "tag": [
      "new",
      "equipment",
      "wholesale"
    ]
  },
  {
    "cost": 300,
    "revenue": 600,
    "tag": [
      "old",
      "equipment"
    ]
  },
  {
    "cost": 800,
    "revenue": 850,
    "tag": [
      "wholesale"
    ]
  }
]
let x = Object.values(a.reduce((acc,{cost,revenue,tag})=>{
    tag.forEach((t) => {
    if(!acc[t])acc[t]={tag:t,cost:0,revenue:0}
    acc[t].revenue+=revenue
    acc[t].cost+=cost
  })
  return acc;
},{}))
console.log(x)

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