nirvair
nirvair

Reputation: 4180

groupBy count in lodash

I have an array of object like this:

[
  {
    rating: 1
  },
  {
    rating: 2
  },
  {
    rating: 3
  },
  {
    rating: 1
  }
]

I want the result like this -

{
  1: 2,
  2: 1,
  3: 1
}

It will be Rating_Value: Count.

How can I do that in lodash? Or if it can be optimized without lodash?

Upvotes: 8

Views: 19365

Answers (3)

ryeballar
ryeballar

Reputation: 30118

You can use lodash#countBy.

var result = _.countBy(data, 'rating');

var data = [
  {
    rating: 1
  },
  {
    rating: 2
  },
  {
    rating: 3
  },
  {
    rating: 1
  }
];

var result = _.countBy(data, 'rating');

console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.14.2/lodash.min.js"></script>

Upvotes: 30

Wojciech Słowacki
Wojciech Słowacki

Reputation: 46

You can do it in pure JS like this:

var myArr = [
  {
    rating: 1
  },
  {
    rating: 2
  },
  {
    rating: 3
  },
  {
    rating: 1
  }
];

var ratingObject = {};

myArr.forEach(function(valueObject) {
   ratingObject[valueObject.rating] = ratingObject[valueObject.rating] ? ratingObject[valueObject.rating] + 1 : 1;
});

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122155

You can use reduce() to get this result.

var data = [{"rating":1},{"rating":2},{"rating":3},{"rating":1}];

var result = data.reduce(function(r, e) {
  r[e.rating] = (r[e.rating] || 0) + 1;
  return r;
}, {});

console.log(result)

Upvotes: 3

Related Questions