Я пытаюсь написать функцию подсчета голосов, у меня есть массив объектов, и каждый объект имеет свойство currentVote
которое имеет значение userId
. Я хочу узнать, у какого пользователяID больше всего голосов. Используя 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
с таким же количеством голосов. На данный момент кажется, что самый маленький идентификатор всегда будет выбран?
Основываясь на вашем вопросе, я считаю, что ваш объект следующий, я использовал сортировку метода массива для сортировки массива в нисходящем порядке и взял первый элемент. Надеюсь это поможет.
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);
Вы можете использовать _.shuffle
и _.first
. Может быть, что-то вроде:
_.chain(votes).countBy()
.groupBy() // added this to get a list of all the ones that have matching vote counts
.toPairs()
.sortBy(0)
.reverse()
.first() // most votes
.last() // get the user ids
.shuffle() // randomize order
.first() // get whatever is first
.value()