因此,在这里,我有一个系统来标识具有最高count的对象,但是正如我们所看到的,有两个具有最高count的对象。我想要做的是取最大的计数(可能很多),然后随机输出一个。我怎样才能做到这一点?

 var objects = [
    {username: 'mark', count: 3},
    {username: 'dave', count: 5},
    {username: 'john', count: 5},
    {username: 'lucy', count: 2},
];

var res = objects.reduce(function(resObj, obj) {
  return resObj.count > obj.count ? resObj : obj
})

console.log(res);


谢谢!

最佳答案

这里的一个好问题是你怎么做

注意:我添加了一些相同的计数,以向您显示这是如何工作的,而不管您有多少匹配项:

Working example

 var objects = [
    {username: 'mark', count: 3},
    {username: 'dave', count: 5},
    {username: 'john', count: 5},
    {username: 'amy', count: 5},
    {username: 'adam', count: 5},
    {username: 'fenty', count: 5},
    {username: 'lucy', count: 2},
];
// make an array to push same counts
var arr = [];

var res = objects.reduce(function(resObj, obj) {
  // keep track of (and set) max count
  var max = Math.max(resObj.count, obj.count);
  // if count is equal push to our array
  if (max === obj.count) {
    arr.push(obj);
  }
  // same code as before
  return resObj.count >= obj.count ? resObj : obj;
});

// get random index from our array
var randIndex = Math.floor(Math.random() * arr.length);

// get random result from our objects that have the same count:
console.log(arr[randIndex]);

09-25 20:01