Rataiczak24
Rataiczak24

Reputation: 1042

Grouping and Getting Count with Lodash

I'm running into a roadblock and cant figure out how to get the count of a field. I'm aware of _.countBy and _.size that are available through Lodash, but for some reason cant come up with the correct values. The subgroup.items array contains values formatted as such:

{
  store name: 'A',
  sku title: '12345'
},
{
  store name: 'A',
  sku title: 09865
},
{
  store name: 'A',
  sku title: 63542
}

My block of code is this:

subGroup.items = _.chain(subGroup.items)
  .groupBy('store name')
  .map(function(v, i) {
    return {
       store: i,
       sku: _.reduce(
         v,
         function(res, val) {
           return res + val['sku title'];
         },
       0
     ),
  };
 })
.value();

How can I return values so that it would show how many sku title's there are for each store like this...

store name: 'A',
sku title: '3'

Upvotes: 3

Views: 587

Answers (1)

David784
David784

Reputation: 7464

If all you want is a count, you should just be able to use v.length instead of using _.reduce(v,...)

var subGroup = {};
subGroup.items = [{
  "store name": 'A',
  "sku title": '12345'
},
{
  "store name": 'A',
  "sku title": 09865
},
{
  "store name": 'A',
  "sku title": 63542
}];


subGroup.items = _.chain(subGroup.items)
  .groupBy('store name')
  .map(function(v, i) {
    return {
       store: i,
       sku: v.length
  };
 })
.value();

console.log(subGroup.items);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Upvotes: 2

Related Questions