JS(jQuery) How to get random element of an array without repetition?

Need a function returns random array element, but not repetitive.
For example, there is an array
var RGBColorsArr = ['rgb(255,255,0)', 'rgb(255,0,0)', 'rgb(51,0,0)', 'rgb(255,0,102)', 'rgb(0,0,51)', 'rgb(0,0,255)', 'rgb(102,0,255)', 'rgb(0,255,255)', 'rgb(51,51,0)', 'rgb(0,0,0)', 'rgb(0,255,0)', 'rgb(0,51,0)'];

contains 12 colors in RGB format.
To get a random value not hard (generate a random index and record its value in a variable):
var getRandomArrIndex = Math.floor( (Math.random() * RGBColorsArr.length) + 0);
var getColor = RGBColorsArr[getRandomArrIndex];

The next value is not repeated, decided that it is possible to remove from the array at index is already resulting value to select randomly from the remaining.
BUT! How is it possible to loop at the N-th function call. So after removing all the elements of the array back to its original version and repeat the procedure.
July 2nd 19 at 17:17
2 answers
July 2nd 19 at 17:19
var randomColor = {
 list: [
 already: [],
 random: function () {
 return this.list[Math.floor(Math.random() * this.list.length)];
 get: function () {

 var color = this.random();

 if (this.already.length >= this.list.length) {
 this.already = [];
 return color;

 if (this.already.indexOf(color) !== -1) {
 return this.get();
 } else {
 return color;


A living example tyk
If the code is possible, at least hypothetically an infinite loop (in this case recursion) is the wrong code - kasandra.Hackett commented on July 2nd 19 at 17:22
: This is a mildly controversial) - Laura_Pacocha commented on July 2nd 19 at 17:25
July 2nd 19 at 17:21
In the General case we can generate random permutation for the set of N elements (in your case 12):
let getRandomPermutation = (n) => {
 let arr = Array.from(Array(n).keys());

 for (let i = (n - 1); i > 0; i--) {
 let j = Math.floor(Math.random() * i);

 [arr[i], arr[j]] = [arr[j], arr[i]];

 return arr;

And then:
let permutation = getRandomPermutation(colors.length);
let temp = colors.slice();

for (let i = 0; i < colors.length; i++) {
 colors[i] = temp[permutation[i]];

You get the sorted random array of colors. If you want to start again - generate a permutation again and the circle closes. Of course you can not generate a permutation separately, and just need to sort an array - here I separated for clarity.


Find more questions by tags Random numbersjQuery