Group the array by occurrence and sort it with Lodash

If this array:

[ { "name" : "lala", "source_ip" : "10.10.10.10" }, { "name" : "lulu", "source_ip" : "10.10.10.11" }, { "name" : "lolo", "source_ip" : "10.10.10.10" } ] 

I would like to group by occurrence and sort it with Lodash to get this result:

 [ { "source_ip" : "10.10.10.10", "count" : 2 }, { "source_ip" : "10.10.10.11", "count" : 1 }, ] 

Here is what I tried:

 app.filter('top10', function() { return function(incidents) { return _.chain(incidents) .countBy("source_ip") .value(); }; }); 

I also tried reducing to and then using grouBy , but it does not work.

Thank you very much.

+5
source share
2 answers

This will help you:

 _(array) .countBy("source_ip") .map(function(count, ip) { return { count: count, source_ip: ip }}) .sortBy('-count') .value() 

Lodash Docs

Notes:

  • sortBy('-count') reverse sorting by property
  • map can iterate over objects and move on to a function key, so you can generate an array from an object
  • _() stands for _.chain()

UPDATE 2017.01.20

We can even do it more elegantly:

 _(array) .countBy("source_ip") .invert() .sortBy('-count') .value() 
+3
source

You can just use

 _.countBy(array, "source_ip"); // => { 10.10.10.10: 2, 10.10.10.11: 1 } 

If you need an array:

 var result=[]; _.forIn(_.countBy(doc, "source_ip"), function(value, key) { result.push({ "source_ip": key, "count": value }); }); 
+1
source

All Articles