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.
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:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.reduce()to create an array of partial sums for each value inweights. - Use
Math.random()to generate a random number andArray.prototype.findIndex()to find the correct index based on the array previously produced. - Finally, return the element of
arrwith 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.