Bada
Bada's Coding

Bada's Coding

Drawing Lots by JavaScript

Bada's photo
Bada
·Sep 9, 2022·

1 min read

If you pass an array and the number of winners, the function will draw lots.

function choose(array, num) {
  const result = [];

  while (result.length < num) {
    const randomIndex = Math.floor(Math.random() * array.length);
    const element = array[randomIndex];
    // The condition below prevents the duplication.
    if (!result.includes(element)) {
      result.push(element);
    }
  }

  return result;
}

const people = ['A', 'B', 'C', 'D', 'E', 'F'];

console.log(choose(people, 3)); // ['B', 'A', 'E']
 
Share this