Search code examples
lodash

How group and count elements by lodash


has data

items = {
                0: {id:1,name:'foo'},
                1: {id:2,name:'bar'},
                2: {id:1,name:'foo'}
            };

I wont get counted elements like this

result = {
                0: {id:1,name:'foo', count:2},
                1: {id:2,name:'bar', count:1}
            };

lodash has function _.countBy(items, 'name') it's got {'foo': 2, 'bar':1}, i need id too.


Solution

  • If pure JS approach is acceptable, you can try something like this:

    Logiic:

    • Loop over array and copy the object and add a property count and set it to 0.
    • Now on every iteration update this count variable.
    • Using above 2 steps, create a hashMap.
    • Now loop over hashMap again and convert it back to array.

    var items = [{
        id: 1,
        name: 'foo'
      }, {
        id: 2,
        name: 'bar'
      }, {
        id: 1,
        name: 'foo'
      }
    ];
    
    var temp = items.reduce(function(p,c){
      var defaultValue = {
        name: c.name,
        id: c.id,
        count: 0
      };
      p[c.name] = p[c.name] || defaultValue
      p[c.name].count++;
      
      return p;
    }, {});
    
    var result = [];
    for( var k in temp ){
      result.push(temp[k]);
    }
    
    console.log(result)