简体   繁体   中英

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.

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM