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

238
Views
How to count values in a nested array using Lodash?

I am trying to calculate the unique count of users.hobbies using Lodash. The data looks like this:

var users = [
  { 'user': 'barney', 'age': 36, 'hobbies': ['soccer','basketball']  },
  { 'user': 'fred',   'age': 40, 'hobbies': ['soccer', 'golf'] },
  { 'user': 'tom',   'age': 25,  'hobbies': ['golf'] }
];

I have tried:

_.countBy(users, 'hobbies');
// { 'soccer,basketball': 1, 'soccer,golf': 1, golf: 1 }

The desired output is:

// { 'soccer':2, 'basketball':1, 'golf':2}

I guess I would need to split the value of users.hobbies but I am not exactly sure how to apply it.

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

0

You can flatten the hobbies before:

const users = [
  { 'user': 'barney', 'age': 36, 'hobbies': ['soccer','basketball']  },
  { 'user': 'fred',   'age': 40, 'hobbies': ['soccer', 'golf'] },
  { 'user': 'tom',   'age': 25,  'hobbies': ['golf'] }
];

const count = _.countBy(users.flatMap(user => user.hobbies));
console.log(count);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

about 4 years ago · Juan Pablo Isaza Report

0

Not sure about lodash, but here is solution with native js

users.reduce((total, el) => {
    el.hobbies.forEach(el => {
        if (el in total) total[el]++
        else total[el] = 1
    })
    return total
}, {})
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!