Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!