Access random array element in javascript without repeating

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 –

Live Demo

Open Live Demo

You may also like –