Access random array element in javascript without repeating

Total
0
Shares
javascript random array element no repeat

In this article we will show you the code to access javascript random array element, no repeat. Without further delay, let’s check out the code –

// Array to store indexes which are left to access. 
// It helps in accessing values without repeating
var alreadyDone = [];

// Function picking random values from array
const randomValueFromArray = (myArray) => {
  // If alreadyDone is empty then fill it will indexes equal
  // to the size of myArray
  if (alreadyDone.length === 0) {
    for (var i = 0; i < myArray.length; i++) alreadyDone.push(i);
  }

  // Generate random number within the range of 
  // length of alreadyDone array
  var randomValueIndex = Math.floor(Math.random() * alreadyDone.length);
  
  // Getting unaccessed index of myArray using above 
  // random number
  var indexOfItemInMyArray = alreadyDone[randomValueIndex];

  // remove this index from alreadyDone array because
  // we are accessing it now.
  alreadyDone.splice(randomValueIndex, 1);

  // Get the value
  return myArray[indexOfItemInMyArray];
};

randomValueFromArray(["a", "b", "c", "d", "e", "f"])

    Tweet this to help others

Similar Article (Opens in new tab) –

In this code we are not changing the input array in any way. So, array will remain as it is.

The process of this function is –

  • We declared a global array alreadyDone which will hold the “not accessed indexes” of input array. So, if we access some value then we will remove the index of that value from this array. For example –

    myArray = [“a”, “b”, “c”, “d”];
    alreadyDone = [0, 1, 2, 3];

    If we access “b” then alreadyDone array will become –
    alreadyDone = [0, 2, 3];
  • Our function randomValueFromArray gets input array as parameter myArray. Next, it checks if alreadyDone is empty and fill it with indexes equal to the length of input array.
  • A random value is picked from alreadyDone.
  • This random value is the index of input array which is not yet accessed.
  • Then we remove this value from alreadyDone array and return corresponding value at index from myArray.

Live Demo

Open Live Demo

You may also like –