JSFiddle - React, Tailwind, and code Playground
JavaScript
function pickRandom(myArray) {
var maxPlays = 0, reverseTotPlays = 0, ipl, picked, revAcc = 0;
// Empty array or bad input param
if (!myArray || !myArray.length) {
return -1;
}
// Calculate the max plays for any song in the list
for (ipl = 0; ipl < myArray.length; ++ipl) {
if (myArray[ipl].plays > maxPlays) {
maxPlays = myArray[ipl].plays;
}
}
maxPlays += 1; // Avoid excluding max songs
// Calculate the reverse weighted total plays
for (ipl = 0; ipl < myArray.length; ++ipl) {
reverseTotPlays += maxPlays - myArray[ipl].plays;
}
// Choose a random number over the reverse weighted spectrum
picked = ~~(Math.random() * reverseTotPlays);
// Find which array member the random number belongs to
for (ipl = 0; ipl < myArray.length; ++ipl) {
revAcc += maxPlays - myArray[ipl].plays;
if (revAcc > picked) {
return ipl;
}
}
return myArray.length - 1;
}
var pp =[{ plays: 3 }, { plays: 1 }, { plays: 2 }]
console.log(pickRandom(pp));