[英]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 : 我想按事件分组并使用Lodash对其进行排序以获得此结果:
[
{
"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. 我也试过减少之前然后使用grouBy但它不起作用。
Thanks a lot. 非常感谢。
This will help you: 这将有助于您:
_(array)
.countBy("source_ip")
.map(function(count, ip) { return { count: count, source_ip: ip }})
.sortBy('-count')
.value()
Notes: 笔记:
sortBy('-count')
reverse sorting by property sortBy('-count')
按属性反向排序 map
can iterate objects and pass to function key, so you can generate array from object map
可以迭代对象并传递给function键,因此可以从object生成数组 _()
notation means _.chain()
_()
表示法表示_.chain()
UPDATE 2017.01.20 更新2017.01.20
We can even do it more elegant: 我们甚至可以做得更优雅:
_(array)
.countBy("source_ip")
.invert()
.sortBy('-count')
.value()
You can simply 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 });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.