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.
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 propertymap
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With