Weighted Random Sampling in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a practical implementation of a weighted sample function in JavaScript. The function returns a random element from an array, with probabilities assigned to each element based on the provided weights. Through this lab, we will learn how to use Array methods such as reduce() and findIndex() along with Math.random() to generate the desired outcome.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28696{{"`Weighted Random Sampling in JavaScript`"}} javascript/data_types -.-> lab-28696{{"`Weighted Random Sampling in JavaScript`"}} javascript/arith_ops -.-> lab-28696{{"`Weighted Random Sampling in JavaScript`"}} javascript/comp_ops -.-> lab-28696{{"`Weighted Random Sampling in JavaScript`"}} javascript/higher_funcs -.-> lab-28696{{"`Weighted Random Sampling in JavaScript`"}} javascript/spread_rest -.-> lab-28696{{"`Weighted Random Sampling in JavaScript`"}} end

How to Get a Weighted Sample from an Array in JavaScript

To randomly get an element from an array based on the provided weights, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.reduce() to create an array of partial sums for each value in weights.
  3. Use Math.random() to generate a random number and Array.prototype.findIndex() to find the correct index based on the array previously produced.
  4. Finally, return the element of arr with the produced index.

Here is the code to achieve this:

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)
  ];
};

You can test this function by passing an array and its corresponding weights as arguments:

weightedSample([3, 7, 9, 11], [0.1, 0.2, 0.6, 0.1]); // 9

Summary

Congratulations! You have completed the Weighted Sample lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like