JSFiddle - React, Tailwind, and code Playground
JavaScript
const movies = [
{ "selected": 0, "title": "Parasite", "weight": 1.0 },
{ "selected": 0, "title": "Avengers: Endgame", "weight": 0.9 },
{ "selected": 0, "title": "Joker ", "weight": 0.8 },
{ "selected": 0, "title": "Once Upon a Time... In Hollywood", "weight": 0.7 },
{ "selected": 0, "title": "Marriage Story", "weight": 0.6 },
{ "selected": 0, "title": "The Irishman", "weight": 0.5 },
{ "selected": 0, "title": "Midsommar", "weight": 0.4 },
{ "selected": 0, "title": "Ad Astra", "weight": 0.3 },
{ "selected": 0, "title": "Yesterday", "weight": 0.2 },
{ "selected": 0, "title": "Cats", "weight": 0.1 },
];
/**
* 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);