Marc Rasmussen Marc Rasmussen - 6 months ago 56
Javascript Question

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?

Answer

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();