Search code examples
javascriptlodash

How can I group by the array using lodash or javascript


An Array is as follows:

let names = [
             'Aditya',
             'Aditya',
             'Aditya',
             'Abhi',
             'Abhi',
             'goyal'
            ]

I want to use lodash function and convert the names array which will return me as

[
  Aditya(3),
  Abhi(2),
  goyal(1)
]

Solution

  • 1) _.countBy the names to produce an object with name/count as the key/value.

    2) Use _.entries to convert the object to a set of nest entry arrays.

    3) _.map over the entries to produce the required output.

    const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
    
    const toString = ([name, count]) => `${name}(${count})`;
    const entries = _.entries(_.countBy(names));
    const result = _.map(entries, toString);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    Alternatively you can use vanilla JS to achieve the same thing in (almost) the same amount of code using reduce, Object.entries, and map.

    const names = ["Aditya","Aditya","Aditya","Abhi","Abhi","goyal"]
    
    const counts = names.reduce((acc, c) => {
      return acc[c] = (acc[c] || 0) + 1, acc;
    }, {});
    
    const toString = ([name, count]) => `${name}(${count})`;
    const entries = Object.entries(counts);
    const result2 = entries.map(toString);
    
    console.log(result2);