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

144
Views
Count double in object and total for each JavaScript

I need a bit help to get the double count and total price for each person. My object

const obj = [
  {'name':'sven','price':'10'},
  {'name':'jan','price':'12'},
  {'name':'john','price':'5'},
  {'name':'nick','price':'13'},
  {'name':'sven','price':'11'},
  {'name':'jan','price':'7'},
  {'name':'nick','price':'9'},
];

From this object I am counting double from key 'name'. e.g. sven 2, jan 1, john 1, nick 2. I use this code for that

const counts = [];
obj.map((x)=>{ 
  counts[x[0]] = (counts[x[0]] || 0) + 1;
});

Now I need also the total count of key 'price' saves together with each person and I can't seem to find a way to do so.

result should be an array of object e.g.

counts = [
  {'person':'sven','count':'2','totalPrice':'21'},
  {'person':'jan','count':'2','totalPrice':'19'}
]

I know how to get double and I know how to count total, but not in the same loop and save as 1 object. If someone could help me a bit pointing the right direction please.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here's an Array.reduce solution which checks whether the array contains an item with the same name property, and if so, increments its totalPrice property by the item's price property and its count property by 1.

const arr = [
  {'name':'sven','price':'10'},
  {'name':'jan','price':'12'},
  {'name':'john','price':'5'},
  {'name':'nick','price':'13'},
  {'name':'sven','price':'11'},
  {'name':'jan','price':'7'},
  {'name':'nick','price':'9'},
];

const result = arr.reduce((a, b) => {
  const found = a.find(e => e.name == b.name);
  if(found){
    found.totalPrice += +b.price;
    found.count++;
  }else{
    a.push({name:b.name, totalPrice: +b.price, count: 1})
  }
  return a
}, [])

console.log(result)

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!