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

208
Views
how to group and sum data in foreach javascript

I have a data in the form of an array object. I will group the data and sum the total based on date and code

const data = [
{code: 8, date:"2022-03-24", total:4},
{code: 8, date:"2022-03-24", total:8},
{code: 8, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-24", total:4},
{code: 9, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-25", total:1},]

results to be expected

const result = [
{code: 8, date:"2022-03-24", total:12},
{code: 8, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-24", total:4},
{code: 9, date:"2022-03-25", total:3},]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can use reduce usually for these grouping problems. I'm taking the combination of code and date to group. something like "8|2022-03-24".

This is how the intermediate object will look like

{
  8|2022-03-24: {
    code: 8,
    date: "2022-03-24",
    total: 12
  },
  8|2022-03-25: {
    code: 8,
    date: "2022-03-25",
    total: 2
  },
  9|2022-03-24: {
    code: 9,
    date: "2022-03-24",
    total: 4
  },
  9|2022-03-25: {
    code: 9,
    date: "2022-03-25",
    total: 3
  }
}

From that object I'm taking the values using Object.values

const data = [
{code: 8, date:"2022-03-24", total:4},
{code: 8, date:"2022-03-24", total:8},
{code: 8, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-24", total:4},
{code: 9, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-25", total:1},]

let grouped = Object.values(data.reduce((acc,{code,date,total})=>{
    acc[code+'|'+date] = acc[code+'|'+date] || {code,date,total:0}
  acc[code+'|'+date].total+=total
  return acc;
},{}))

console.log(grouped)

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!