按出现次数对数组进行分组,并使用Lodash对其进行排序

时间:2023-01-29 15:58:22

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()

Lodash docs

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

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()

Lodash docs

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

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 });
});