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

235
Views
Get one value by frequency in JS hash without losing the other keys and values

I am learning Javascript and I have a hash of users like this:

const users = [{id: 1, firstName: "Jose", revenue: 3700, country: "Colombia"}, {id: 2, firstName: "Rodney", revenue: 9100, country: "Germany"}, {id: 3, firstName: "Danny", revenue: 0, country: "United States"},  { id: 4, firstName: "Birgit", revenue: 7700, country: "Germany"}, {id: 5, firstName: "Audra", revenue: 0, country: "Germany"},{id: 6, firstName: "Doreatha", revenue: 0, country: "Colombia"}]

and I'd like to get the frequencies of one key (country) as well as the sum of another key (revenue) of the two most frequent countries. I tried .reduce to get the countries, but the trouble is that it returns an object with no revenues. Here is my code:

const usersByCountry = users.reduce((c, u) => {
  c[u.country] = c[u.country] + 1 || 1;
  return c;
}, {});

And here's the output :

Object { "Colombia": 2, "Germany": 3, "United States": 1 }

Is it even possible to exploit .reduce for this or am I on the wrong track?

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

0

You can add all required properties to the accumulator object in reduce:

const users = [{id: 1, firstName: "Jose", revenue: 3700, country: "Colombia"}, {id: 2, firstName: "Rodney", revenue: 9100, country: "Germany"}, {id: 3, firstName: "Danny", revenue: 0, country: "United States"},  { id: 4, firstName: "Birgit", revenue: 7700, country: "Germany"}, {id: 5, firstName: "Audra", revenue: 0, country: "Germany"},{id: 6, firstName: "Doreatha", revenue: 0, country: "Colombia"}]

const usersByCountry = users.reduce((acc, u) => {
  acc[u.country] = {
    frequency: (acc[u.country]?.frequency ?? 0) + 1,
    revenue: (acc[u.country]?.revenue ?? 0) + u.revenue
  };
  return acc;
}, {});

console.log(usersByCountry);

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!