If I understand right then you're just looking for a permutation (i.e. the numbers randomised with no repeats) of the numbers 1-10? Maybe try generating a randomised list of those numbers, once, at the start, and then just working your way through those?

This will calculate a random permutation of the numbers in nums:

var nums = [1,2,3,4,5,6,7,8,9,10],
    ranNums = [],
    i = nums.length,
    j = 0;

while (i--) {
    j = Math.floor(Math.random() * (i+1));
    ranNums.push(nums[j]);
    nums.splice(j,1);
}

So, for example, if you were looking for random numbers between 1 - 20 that were also even, then you could use:

nums = [2,4,6,8,10,12,14,16,18,20];

Then just read through ranNums in order to recall the random numbers.

This runs no risk of it taking increasingly longer to find unused numbers, as you were finding in your approach.

EDIT: After reading this and running a test on jsperf, it seems like a much better way of doing this is a Fisher–Yates Shuffle:

function shuffle(array) {
    var i = array.length,
        j = 0,
        temp;

    while (i--) {

        j = Math.floor(Math.random() * (i+1));

        // swap randomly chosen element with current element
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;

    }

    return array;
}

var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);

Basically, it's more efficient by avoiding the use of 'expensive' array operations.

BONUS EDIT: Another possibility is using generators (assuming you have support):

function* shuffle(array) {

    var i = array.length;

    while (i--) {
        yield array.splice(Math.floor(Math.random() * (i+1)), 1)[0];
    }

}

Then to use:

var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);

ranNums.next().value;    // first random number from array
ranNums.next().value;    // second random number from array
ranNums.next().value;    // etc.

where ranNums.next().value will eventually evaluate to undefined once you've run through all the elements in the shuffled array.

Overall this won't be as efficient as the Fisher–Yates Shuffle because you're still splice-ing an array. But the difference is that you're now doing that work only when you need it rather than doing it all upfront, so depending upon your use case, this might be better.

Answer from Ben Jackson on Stack Overflow
Top answer
1 of 16
61

If I understand right then you're just looking for a permutation (i.e. the numbers randomised with no repeats) of the numbers 1-10? Maybe try generating a randomised list of those numbers, once, at the start, and then just working your way through those?

This will calculate a random permutation of the numbers in nums:

var nums = [1,2,3,4,5,6,7,8,9,10],
    ranNums = [],
    i = nums.length,
    j = 0;

while (i--) {
    j = Math.floor(Math.random() * (i+1));
    ranNums.push(nums[j]);
    nums.splice(j,1);
}

So, for example, if you were looking for random numbers between 1 - 20 that were also even, then you could use:

nums = [2,4,6,8,10,12,14,16,18,20];

Then just read through ranNums in order to recall the random numbers.

This runs no risk of it taking increasingly longer to find unused numbers, as you were finding in your approach.

EDIT: After reading this and running a test on jsperf, it seems like a much better way of doing this is a Fisher–Yates Shuffle:

function shuffle(array) {
    var i = array.length,
        j = 0,
        temp;

    while (i--) {

        j = Math.floor(Math.random() * (i+1));

        // swap randomly chosen element with current element
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;

    }

    return array;
}

var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);

Basically, it's more efficient by avoiding the use of 'expensive' array operations.

BONUS EDIT: Another possibility is using generators (assuming you have support):

function* shuffle(array) {

    var i = array.length;

    while (i--) {
        yield array.splice(Math.floor(Math.random() * (i+1)), 1)[0];
    }

}

Then to use:

var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);

ranNums.next().value;    // first random number from array
ranNums.next().value;    // second random number from array
ranNums.next().value;    // etc.

where ranNums.next().value will eventually evaluate to undefined once you've run through all the elements in the shuffled array.

Overall this won't be as efficient as the Fisher–Yates Shuffle because you're still splice-ing an array. But the difference is that you're now doing that work only when you need it rather than doing it all upfront, so depending upon your use case, this might be better.

2 of 16
7
//random number without repetition in JavaScript, Just in one line;
//it can be used as _id;
//it not need to store or check;

const myRnId = () => parseInt(Date.now() * Math.random());

console.log(myRnId()); // any random number included timeStamp;

🌐
freeCodeCamp
forum.freecodecamp.org › javascript
How to make Math.random not repeat same numbers - JavaScript - The freeCodeCamp Forum
August 30, 2020 - Hi! I was trying to make an app and I need to make it show 4 random items from an array but the problem is that with Math.random there’s a possibility to have the same item twice or more times. Does anyone know how to s…
Discussions

create random numbers with out them repeating in javascript
Moises Miguel is having issues with: Basically I want to create random numbers up to 10. and put them in an array, but i dont want any of the numbers to repeat. I have been... More on teamtreehouse.com
🌐 teamtreehouse.com
1
April 29, 2017
Generate Non-Repeating Random Number From A Set - JavaScript - SitePoint Forums | Web Development & Design Community
I am trying to generate a random number from a set of numbers but it does not seem to be working. Basically what I did was I randomly generated a number from a set and kept track of each generated number so that it won’t be generated again. To try to prevent duplicates from being generated, ... More on sitepoint.com
🌐 sitepoint.com
0
February 13, 2018
javascript - Prevent repetitive random numbers - Code Review Stack Exchange
Is this a good way to prevent two sequential numbers from repeating, or is there a better, more efficient way of doing this? By efficient, I mean a less CPU and memory consuming process. while (ra... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
September 5, 2014
Random number generator without dupes in Javascript? - Stack Overflow
I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish. Any ideas? More on stackoverflow.com
🌐 stackoverflow.com
🌐
DEV Community
dev.to › sagdish › generate-unique-non-repeating-random-numbers-g6g
Generate unique (non-repeating) random numbers - DEV Community
November 23, 2020 - Since we decrease range in each iteration: range - i so numbers from upper end of array will not be picked. At the end we just return array of unique random numbers.
🌐
Waimin
waimin.me › generate_unique_randoms
Generating non-repeating (unique) random numbers in JavaScript | Wai Min's Blog
If we use Math.floor() for Math.random() * 10;, we will get the range of [ 0 to 9]. For Math.round() we will get [ 1 to 10]. For simplicity sake, let's just use the Math.floor() We can already see some numbers are repeated. A dirty solution would be to check if the generated number already exists before pushing it to the array.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-create-an-array-containing-non-repeating-elements-in-javascript
How to create an array containing non-repeating elements in JavaScript ? - GeeksforGeeks
July 3, 2024 - // You can take this value from user const n = 5 // Initial empty array const arr = []; // Null check if (n == 0) { console.log(null) } do { // Generating random number const randomNumber = Math .floor(Math.random() * 100) + 1 // Pushing into the array only // if the array does not contain it if (!arr.includes(randomNumber)) { arr.push(randomNumber); } } while (arr.length < n); // Printing the array elements console.log(arr)
Find elsewhere
🌐
ThisCodeWorks
thiscodeworks.com › generate-random-number-without-repetition-javascript-array-random-randomarray-dom › 60793ffc66aefe0014ebb821
Generate Random Number without repetition | thiscodeWorks
Saved by @thepuskar #javascript #array #random #randomarray #dom · let clickMe = document.querySelector('button'); function getRandomNumber(min, max) { let totalEle = max - min + 1; let result = Math.floor(Math.random() * totalEle) + min; return result; } function createArrayOfNumber(start, end) { let myArray = []; for (let i = start; i <= end; i++) { myArray.push(i); } return myArray; } let numbersArray = createArrayOfNumber(1, 10); clickMe.addEventListener('click', () => { if (numbersArray.length === 0) { console.log('No more random number'); return; } let randomIndex = getRandomNumber(0, numbersArray.length - 1); let randomNumber = numbersArray[randomIndex]; numbersArray.splice(randomIndex, 1); console.log(randomNumber); }); content_copyCOPY https://playcode.io/757523/ content_copy ·
🌐
CodePen
codepen.io › calebdeji › pen › NQrOXZ
Generating array of random numbers without repetition
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
🌐
Quora
quora.com › How-do-I-generate-random-numbers-without-repetition-using-switchcase-in-JavaScript
How to generate random numbers without repetition using switchcase in JavaScript - Quora
But I will mention three ways to achieve this. * Worst way possible [code]function DistinctRandomNumberGenerator(min, max) { min = Number(min) || 0; max = Number(max) || 10; var keyTracker = {}; var range = max - min; fu...
🌐
SitePoint
sitepoint.com › javascript
Generate Non-Repeating Random Number From A Set - JavaScript - SitePoint Forums | Web Development & Design Community
February 13, 2018 - I am trying to generate a random number from a set of numbers but it does not seem to be working. Basically what I did was I randomly generated a number from a set and kept track of each generated number so that it won’t be generated again. To try to prevent duplicates from being generated, ...
Top answer
1 of 6
10

In practice, your code will be fine. In theory, it is not guaranteed to terminate, but the probability of that happening is literally negligible.

However, what you are doing is picking a random integer between 1 and 3 (both inclusive), with the number not repeating. With only three possibilities, we could draw up a state machine:

states = {
  1: [2, 3],
  2: [1, 3],
  3: [1, 2] };
if (lastRandom === undefined) {
    random = Math.floor(Math.random() * 3) + 1;
}
else {
    random = states[lastRandom][Math.floor(Math.random() * 2)];
}
lastRandom = random;

Unfortunately, that involves generating all the states first, which is impractical for larger ranges. There, we could use this more clever approach:

var min = 1;
var max = 3;
if (lastRandom === undefined) {
    random = Math.floor(Math.random() * (max - min + 1)) + min;
}
else {
    random = Math.floor(Math.random() * (max - min    )) + min;
    if (random >= lastRandom) random += 1;
}
lastRandom = random;

So if we are choosing the first number, everything works as usual. But for any subsequent number, we choose an integer from a set one smaller (to reflect that one number, the lastRandom, can't be chosen). If the random number obtained like this is less than the lastRandom, it can be used as is. Otherwise it has to be incremented by one, so that the lastRandom has been skipped.

Test to compare code:

2 of 6
2

You can do this without checking what the previous selection was. On the first iteration, you select a number from 1 to n, call this r. However, subsequent iterations should select a number from 1 to (n - 1), call this rn. The next random number in the sequence is then ((r-1 + nr) % n) + 1

It works like this: imagine the numbers 1:n are stored in array. If you start at some position x, you get to the next position x, but not back to x, by adding n-1 to x (but not going past the nth index by starting over at the beginning when you pass it, hence the modulus operation). That's kind of hard to visualize without a diagram and i'm not good at making internet forum diagrams.

🌐
Quora
quora.com › How-do-I-return-non-repeating-random-numbers-in-JavaScript
How to return non-repeating random numbers in JavaScript - Quora
Answer: Well, I don’t know JavaScript, but if you want to avoid repetition (for example, to simulate a lottery drawing), you can do something like this: * Generate a list, array, or similar structure, with the numbers you want to choose from.
Top answer
1 of 11
13

There are a number of ways you could achieve this.

Solution A: If the range of numbers isn't large (let's say less than 10), you could just keep track of the numbers you've already generated. Then if you generate a duplicate, discard it and generate another number.

Solution B: Pre-generate the random numbers, store them into an array and then go through the array. You could accomplish this by taking the numbers 1,2,...,n and then shuffle them.

shuffle = function(o) {
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

var randorder = shuffle([0,1,2,3,4,5,6]);
var index = 0;

setInterval(function() {
    $('.foo:nth-of-type('+(randorder[index++])+')').fadeIn(300);
}, 300);

Solution C: Keep track of the numbers available in an array. Randomly pick a number. Remove number from said array.

var randnums = [0,1,2,3,4,5,6];

setInterval(function() {
    var m = Math.floor(Math.random()*randnums.length);
    $('.foo:nth-of-type('+(randnums[m])+')').fadeIn(300);
    randnums = randnums.splice(m,1);
}, 300);
2 of 11
3

You seem to want a non-repeating random number from 0 to 6, so similar to tskuzzy's answer:

var getRand = (function() {
  var nums = [0, 1, 2, 3, 4, 5, 6];
  var current = [];

  function rand(n) {
    return (Math.random() * n) | 0;
  }
  return function() {
    if (!current.length) current = nums.slice();
    return current.splice(rand(current.length), 1)[0];
  }
}());


// Run 3 times
for (let i=0; i<3; i++) {
  console.log('run ' + i);
  for (let j=0; j<7; j++) {
    console.log(getRand());
  }
}

It will return the numbers 0 to 6 in random order. When each has been drawn once, it will start again.

🌐
CopyProgramming
copyprogramming.com › howto › generating-non-repeating-random-numbers-in-js
JavaScript Non-Repeating Random Numbers: Complete Guide with Best Practices 2026
December 21, 2025 - Generating non-repeating random numbers is a solved problem in JavaScript with multiple proven approaches. For most applications, the Fisher-Yates shuffle algorithm combined with immutable array copying provides the optimal balance of performance, clarity, and correctness.