Weighted sample

Angelos Chalaris · JavaScript, Array, Random · Oct 22, 2020

Gets a random element from an array, using the provided weights as the probabilities for each element.

const weightedSample = (arr, weights) => {
  let roll = Math.random();
  return arr[
    weights
      .reduce(
        (acc, w, i) => (i === 0 ? [w] : [...acc, acc[acc.length - 1] + w]),
        []
      )
      .findIndex((v, i, s) => roll >= (i === 0 ? 0 : s[i - 1]) && roll < v)
  ];
};
weightedSample([3, 7, 9, 11], [0.1, 0.2, 0.6, 0.1]); // 9

Recommended snippets