如何按属性计算数组中的对象数?

时间:2019-11-07 10:56:49

标签: javascript

我正在尝试使拥有最多消息的用户简单地排在前3名。 到目前为止,我已经能够将用户和消息分组到一个对象数组中

let data = [ { message: 'fsaasfafs', user: 'John' },
  { message: 'asgsgaasgags', user: 'John' },
  { message: 'asgsgaasgags', user: 'John' },
  { message: 'asgsgaasgags', user: 'Smith' },
  { message: 'asgsgaasgags', user: 'Samantha' },
  { message: 'asgsgaasgags', user: 'Luis' },
  { message: 'asgsgaasgags', user: 'Samantha' }]

console.log(data);

在这种情况下,前3名将是 John-3;萨曼莎-2;史密斯或路易斯(无所谓)-1 我想要一张以用户为键和消息数量的地图。

请帮忙吗?

2 个答案:

答案 0 :(得分:1)

    let data = [ { message: 'fsaasfafs', user: 'John' },
      { message: 'asgsgaasgags', user: 'John' },
      { message: 'asgsgaasgags', user: 'John' },
      { message: 'asgsgaasgags', user: 'Smith' },
      { message: 'asgsgaasgags', user: 'Samantha' },
      { message: 'asgsgaasgags', user: 'Luis' },
      { message: 'asgsgaasgags', user: 'Samantha' }];
      
    let topM = Object.entries(data.reduce((acc, c) => { acc[c.user] = (acc[c.user] || 0 ) + 1; return acc;},{})).sort(function (a, b) { return b[1] - a[1];}).slice(0, 3);
    console.log(topM);

希望这对您有帮助!

答案 1 :(得分:0)

您可能希望获得每条用户消息的计数

  1. 然后,您可以使用Array#reduceArray#filter 来计数每个用户消息(这将与每个用户的数组中的用户计数相匹配)

let data = [ { message: 'fsaasfafs', user: 'John' },
  { message: 'asgsgaasgags', user: 'John' },
  { message: 'asgsgaasgags', user: 'John' },
  { message: 'asgsgaasgags', user: 'Smith' },
  { message: 'asgsgaasgags', user: 'Samantha' },
  { message: 'asgsgaasgags', user: 'Luis' },
  { message: 'asgsgaasgags', user: 'Samantha' }]
  
 let user_list = data.reduce((a,b,c,d)=>{
   if(Object.keys(a).indexOf(b.user) == -1){
    a[b.user] = d.filter(i=>i.user == b.user).length
   }
   return a
 },{})
 
 console.log(user_list)