JavaScript - 随机输出众多热门点击之一

时间:2016-05-08 23:43:02

标签: javascript random reduce

所以这里我有一个系统可以识别具有最高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);

谢谢!

3 个答案:

答案 0 :(得分:3)

这里的好问题是如何做到这一点

注意:我添加了一些相同的计数,以向您展示无论您有多少匹配,这是如何工作的:

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

答案 1 :(得分:1)

以下是使用简单for循环的答案。返回随机最亮的对象

function getHighest(objects) {
    var highest = 0;
    var heighestArr = [];
    // first get highest index
    for(var i=1; i<objects .length;i++){
         if(objects[i].count > objects[highest].count){
              highest= i;
         }
    }
    // then add all the highest ones in an array  
    for(var i=0; i<objects .length;i++){
         if(objects[i].count === objects[highest].count){
              heighestArr.push(objects[i])
         }
    }
    // return random from that array
    return heighestArr[Math.floor(Math.random()*heighestArr.length)];
}

答案 2 :(得分:0)

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

var res = objects.slice(1).reduce(function(resObj, obj) {
  if (resObj[0].count > obj.count) {
    return resObj;
  } else if (resObj[0].count === obj.count) {
    return [...resObj, obj];
  } else {
    return [obj]
  }
}, [objects[0]])

var randomElement = function(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

console.log(randomElement(res));

未经测试,但这是基本想法。