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.
非常感谢。
2 个解决方案
#1
3
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 -
map
can iterate objects and pass to function key, so you can generate array from object -
_()
notation means_.chain()
sortBy(' - count')按属性反向排序
map可以迭代对象并传递给function键,因此可以从object生成数组
_()表示法表示_.chain()
UPDATE 2017.01.20
We can even do it more elegant:
我们甚至可以做得更优雅:
_(array)
.countBy("source_ip")
.invert()
.sortBy('-count')
.value()
#2
1
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 });
});
#1
3
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 -
map
can iterate objects and pass to function key, so you can generate array from object -
_()
notation means_.chain()
sortBy(' - count')按属性反向排序
map可以迭代对象并传递给function键,因此可以从object生成数组
_()表示法表示_.chain()
UPDATE 2017.01.20
We can even do it more elegant:
我们甚至可以做得更优雅:
_(array)
.countBy("source_ip")
.invert()
.sortBy('-count')
.value()
#2
1
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 });
});