0

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.

1
  • 1
    Use: _.countBy(_.flatten(users.map(u => u.hobbies))) Commented Oct 20, 2021 at 11:38

2 Answers 2

5

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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
}, {})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.