JSFiddle - React, Tailwind, and code Playground
JavaScript
const movies = [
{ "selected": 0, "title": "Parasite", "weight": 0.91 },
{ "selected": 0, "title": "Avengers: Endgame", "weight": 0.89 },
{ "selected": 0, "title": "Joker ", "weight": 0.85 },
{ "selected": 0, "title": "Once Upon a Time... In Hollywood", "weight": 0.76 },
{ "selected": 0, "title": "Marriage Story", "weight": 0.74 },
{ "selected": 0, "title": "The Irishman", "weight": 0.71 },
{ "selected": 0, "title": "Midsommar", "weight": 0.61 },
{ "selected": 0, "title": "Ad Astra", "weight": 0.57 },
{ "selected": 0, "title": "Yesterday", "weight": 0.49 },
{ "selected": 0, "title": "Cats", "weight": 0.25 },
];
/**
* Get random movie from our list
*
* @param array Movie[]
* @return Movie
*/
function getRandomMovie(movies) {
const sum = movies.reduce((accumulator, movie) =>
(isNaN(accumulator) ? movie.weight : accumulator) + movie.weight);
let target = Math.random() * sum;
for (let movie of movies) {
if ((target -= movie.weight) < 0) {
return movie;
}
}
// Unreachable
return movies[0];
}
// Test iterations
for (let i = 0, l = 100; i < l; i++) {
const movie = getRandomMovie(movies);
// Increment how many times this movie was selected for demonstrations
movie.selected ++;
// Report
console.log(i, 'Movie', movie.title);
}
// Log our movie array to see how many times each was picked
console.log(movies);