Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Created January 2, 2022 12:02
Show Gist options
  • Select an option

  • Save mitchallen/442df2791d8757a6f5ff56263c1a2fe0 to your computer and use it in GitHub Desktop.

Select an option

Save mitchallen/442df2791d8757a6f5ff56263c1a2fe0 to your computer and use it in GitHub Desktop.
JavaScript example of random picking from a list.
// Author: Mitch Allen
// File: pickone.js
let pickOne = (list) => list[Math.floor(Math.random() * list.length)]
let LIMIT = 5;
let list = [...Array(LIMIT)].map(() => Math.random());
console.log(list);
let item = pickOne(list);
console.log("PICK: ", item);
// check occurrences
let PICK_LIMIT = 100;
let picks = [...Array(PICK_LIMIT)].map(() => pickOne(list));
const occurrences = picks.reduce(function (acc, curr) {
return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc
}, {});
console.log("PICK OCCURRENCES:")
console.log(occurrences);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment