Published on

Generate Unique Random Numbers in JavaScript

Authors

Sometimes, you might want to generate unique random numbers but unfortunately, it does not have a specific built-in function for that.

Math.random() gives us random numbers but it does not keep track of the old numbers and so it cannot guarantee uniqueness in the result.

Here is how to generate unique numbers using unique-random package.

Dependency

npm install unique-random

Snippet

import uniqueRandom from 'unique-random';

const random = uniqueRandom(1, 25);

console.log(random(), random(), random()); // 18 4 10

API

uniqueRandom(minimum, maximum)

Returns a function that returns a unique number, every time we call it.

Happy generating numbers!