JS计算数组中的出现次数并按最高排序

时间:2017-11-04 16:07:17

标签: javascript arrays

我正在尝试编写一个计票功能,我有一个对象数组,每个对象都有一个名为currentVote的属性,其值为userId。我想知道哪个userID投票最多。使用lodash这是我到目前为止所得到的:

function countVotes(players) {
  return new Promise(function(resolve, reject) {
    //votes should be empty, filled it with some sample values
    let votes = ['312139659792875521','360445341989863434', '312139659792875521','360445341989863435','1','9999999999999999999999'];
    for (let i = 0, j = players.length; i < j; i++) {
      votes.push(players[i].currentVote);
    }
    let tally = _.chain(votes)
      .countBy()
      .toPairs()
      .sortBy(1).reverse()
      .map(0)
      .value()[0];
    resolve(tally);
  });

如果我有多个具有相同投票数的userIds,我该如何选择随机值。目前似乎总是会选择最小的身份证?

2 个答案:

答案 0 :(得分:3)

根据你的问题,我相信你的对象如下,我使用数组方法排序按降序对数组进行排序并拾取第一个元素。希望这可以帮助。

let players = [{
                 "userId":1,
                 "currentVotes":2220
               },
               {
                 "userId":2,
                 "currentVotes":383830
               },
               {
                 "userId":3,
                 "currentVotes":6894740
               },
               {
                 "userId":4,
                 "currentVotes":6894740
               },
               {
                 "userId":5,
                 "currentVotes":1
               }
              ];


function getHighestVoteByRandowm(players){

    let arrSameVotes = [];

    let i = 0;
    do{
        arrSameVotes.push(players[i]);
        temp = players[i].currentVotes;
        i++;
    }while(players[i].currentVotes == temp);

    let rndTill = arrSameVotes.length - 1;
    let rndVal = Math.round(Math.random() * rndTill);

    return arrSameVotes[rndVal];

}

function sortVotes(a,b){
    return b.currentVotes - a.currentVotes;
}

let highestVotesPlayer = getHighestVoteByRandowm(players.sort(sortVotes));

console.log(highestVotesPlayer);

答案 1 :(得分:1)

您可以使用*(p->array+x)_.shuffle。也许是这样的:

_.first