Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group an array by occurrences and sort it with Lodash

If have 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 occurrences 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 to reduce before and then use grouBy instead but it is not working.

Thanks a lot.

like image 925
fallais Avatar asked Jun 06 '16 11:06

fallais


1 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 objects and pass to function key, so you can generate array from object
  • _() notation means _.chain()

UPDATE 2017.01.20

We can even do it more elegant:

_(array)
  .countBy("source_ip")
  .invert()
  .sortBy('-count')
  .value()
like image 139
Max Avatar answered Oct 12 '22 23:10

Max