Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash count unique of field

I have an array of 500 objects each object looks like this:

{name: 'Hello', phone_num: '1234'}

Now i wish to find out how many there is of each name. So i wish to convert my array into the following:

[{name: 'Hello', count:15}, {name:'Marc', count:5}]

So i wish thinking of using lodash for this but looking at their documentation i haven't been able to find an answer.

They have something called countBy but it doesnt seem to be sufficient for this issue.

Can anyone help me out?

like image 344
Marc Rasmussen Avatar asked May 20 '16 13:05

Marc Rasmussen


2 Answers

You can make use of groupBy() to group them by name and then map() each grouped items to return the necessary count and names.

var result = _(data)
  .groupBy('name')
  .map((items, name) => ({ name, count: items.length }))
  .value();

var data = [
  { name: 'Hello', phone_num: '1234'},
  { name: 'Hello', phone_num: '1234'},
  { name: 'Hello', phone_num: '1234'},
  { name: 'Hello', phone_num: '1234'},
  { name: 'Hello', phone_num: '1234'},
  { name: 'Hello', phone_num: '1234'},
  { name: 'Hello', phone_num: '1234'},
  
  { name: 'Marc', phone_num: '5432'},
  { name: 'Marc', phone_num: '5432'},
  { name: 'Marc', phone_num: '5432'},
  { name: 'Marc', phone_num: '5432'},
  { name: 'Marc', phone_num: '5432'},
  { name: 'Marc', phone_num: '5432'},
  { name: 'Marc', phone_num: '5432'},
  { name: 'Marc', phone_num: '5432'},
  
  { name: 'Sam', phone_num: '76532'},
  { name: 'Sam', phone_num: '76532'},
  { name: 'Sam', phone_num: '76532'},
  { name: 'Sam', phone_num: '76532'}
  
];
  
var result = _(data)
  .groupBy('name')
  .map((items, name) => ({ name, count: items.length }))
  .value();
  
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

UPDATE:

The ES5 Version would be:

var result = _(data)
  .groupBy('name')
  .map(function(items, name) { 
     return { name: name, count: items.length };
  }).value();
like image 80
ryeballar Avatar answered Oct 20 '22 00:10

ryeballar


My version:

var result = _(data)
  .countBy('name')
  .map((count, name) => ({ name, count }))
  .value();
like image 11
Alexey Ten Avatar answered Oct 20 '22 02:10

Alexey Ten