JavaScript random with weight?

I have a JavaScript array that I want to randomize. How can you add weight to that randomization? For example, let’s say I had a list of songs rated from 1 to 10. I want to randomize the list to play random, but I want songs rated 3 to likely be lower in the list than songs rated 7. How could I do this in JavaScript?

define “likely be lower”.

function weightrandom(probabilities) {
  let shot = Math.random();
  return probabilities.map((val,ind,arr) => { arr[ind] = (ind == 0 ? 0 : arr[ind-1])+val; return arr[ind] }).map(x => x >= shot).indexOf(true);
}

#UnnecessarilyLongAlmostOneLiner.

2 Likes

Amazing solution! Super helpful. Thank You!