Published on

How to Take a Random Sample from a List in JavaScript

Authors

If you need to take a random sample from a list to, for instance generate a random name or value, in JavaScript, there is a simple way to do this in vanilla JS without extra dependencies, using the Math module.

You can split it up into 2 steps: 1) returning a random number between 0 and the length of the list you are sampling, and then 2) calling the list with the random index. Math.random() takes care of the pseudo-randomness, and Math.floor() makes sure this is an integer to be used as our index.

// 1
function random(max) {
  const min = 0;
  return min + Math.floor(Math.random() * (max - min + 1));
}

// 2
function sampleOne(list) {
	return list[random(list.length - 1)];
}

const list = ['a', 'b', 'c', 'd', 'e'];
const rand = sampleOne(list);
console.log(rand);

And as a simple one-liner:

const list = ['a', 'b', 'c', 'd', 'e'];
const randSample = list[Math.floor(Math.random() * list.length)];
console.log(randSample);

One of the use cases of this is to generate a combination of randomly chosen strings, to generate a random name for instance. If you just want to get a docker like random unique name for a project, you can use an already compiled version of this function turned random name generator, hosted here. 😉 Happy coding!