0

I have a object like so:

{
  "user1": 200,
  "user2": 50,
  "user3": 250,
  "user4": 100
}

I would want to randomly pick one of these users based off of the value associated to their property. So in this scenario, user1 should have a 33.33% chance of winning, user2 should have 8.33% and so on. How could I do that?

John Landon
  • 345
  • 1
  • 3
  • 10
  • Concept is called "weighted random number" and there are plenty of questions discussing it/providing copy-paste ready implementations - i.e. one linked as suggested duplicate. – Alexei Levenkov Jan 21 '17 at 02:59

1 Answers1

1

You just pick a number between 0 and N where N is the sum of all weights, then find where that weight lies:

function selectByWeight(list) {
  var total = 0;

  Object.keys(list).forEach(function(k) {
    total += list[k];
  });

  var selection = Math.random() * total;
  var selected;
  var count = 0;

  Object.keys(list).forEach(function(k) {
    count += list[k];

    if (count > selection && !selected) {
      selected = k;
    }
  });

  return selected;
}

var users = {
  "user1": 200,
  "user2": 50,
  "user3": 250,
  "user4": 100
}

console.log(selectByWeight(users));
tadman
  • 208,517
  • 23
  • 234
  • 262