Generating n random numbers between a range - JavaScript

We are required to write a JavaScript function that takes in a number, say n, and an array of two numbers that represents a range. The function should return an array of n random elements all lying between the range provided by the second argument.

Understanding the Problem

The challenge is to generate unique random numbers within a specified range. We need two helper functions: one to generate a single random number between two values, and another to collect n unique random numbers.

Example Implementation

Following is the code −

const num = 10;
const range = [5, 15];

const randomBetween = (a, b) => {
    return ((Math.random() * (b - a)) + a).toFixed(2);
};

const randomBetweenRange = (num, range) => {
    const res = [];
    for(let i = 0; i < num; ){
        const random = randomBetween(range[0], range[1]);
        if(!res.includes(random)){
            res.push(random);
            i++;
        };
    };
    return res;
};

console.log(randomBetweenRange(num, range));

Output

This will produce the following output in console −

[
  '13.25', '10.31',
  '11.83', '5.25',
  '6.28',  '9.99',
  '6.09',  '7.58',
  '12.64', '8.92'
]

This is just one of the many possible outputs.

Let us run again to get a different random output −

[
  '5.29', '7.95',
  '11.61', '7.83',
  '10.56',  '7.48',
  '12.96',  '6.92',
  '8.98', '9.43'
]

How It Works

The randomBetween() function uses Math.random() to generate a decimal between 0 and 1, then scales it to the desired range using the formula: (Math.random() * (b - a)) + a. The result is fixed to 2 decimal places.

The main function randomBetweenRange() keeps generating random numbers until it collects n unique values, using includes() to check for duplicates.

Alternative Approach: Allowing Duplicates

If duplicates are acceptable, the implementation becomes simpler:

const randomBetweenRangeSimple = (num, range) => {
    const res = [];
    for(let i = 0; i < num; i++){
        const random = randomBetween(range[0], range[1]);
        res.push(random);
    }
    return res;
};

console.log(randomBetweenRangeSimple(5, [1, 10]));
[ '3.47', '8.92', '1.56', '9.23', '4.81' ]

Conclusion

This approach generates n unique random numbers within a specified range using Math.random() and duplicate checking. The method works well for reasonable ranges and quantities.

Updated on: 2026-03-15T23:18:59+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements