Skip to content Skip to sidebar Skip to footer

Select Random Item From Array & Remove It, Restart Once Array Is Empty

I'm trying to set select a random item from an array. Once selected, it needs to be removed from the array so it does not get selected again. Finally, once the array is emptied, th

Solution 1:

This probably will not run in this sandbox (use of localstore), but I think it should work if you tried it.

// -------------------------------// see: http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array// -------------------------------function_shuffle (array) {
  for (var i = array.length - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var temp = array[i];
      array[i] = array[j];
      array[j] = temp;
  }
  return array;
}
// -------------------------------// -------------------------------// Get the next "random" item.// -------------------------------var randomItem  = (function(allItems){
  var _key = "array";
  var _currentItems = [];

  try {
    _currentItems = JSON.parse(localStorage.getItem(_key) || "[]");
  } catch (e) {
    _currentItems = [];
  }

  if (!Array.isArray(_currentItems) || _currentItems.length === 0 ) {
    console.log("resetting");
    _currentItems = _shuffle(allItems.slice());
  }

  var _selectedItem = _currentItems.pop();
  localStorage.setItem(_key, JSON.stringify(_currentItems));

  return _selectedItem;
})(["apple", "orange", "banana"]);
// -------------------------------console.log(randomItem);

A more bare bones version [ with _shuffle() from above ] might be just:

var nextItem  = (function(all){
  var _key = "array";
  var _current = JSON.parse(localStorage.getItem(_key) || "[]");
  if (_current.length === 0) { _current = _shuffle(all.slice()); }

  var _selected = _current.pop();
  localStorage.setItem(_key, JSON.stringify(_current));

  return _selected;
})(["apple", "orange", "banana"]);

Solution 2:

I think the problem you are having is caused by the fact that you are passing the value you get from the array the the splice() function when it is actually expecting an index. Checkout the docs page. so what you would do instead is:

// Get array from sessionStorage
myArray = JSON.parse(sessionStorage.getItem("array"));

// If array does not exist in sessionStorage, set itif (myArray === null) {
  sessionStorage.setItem("array", JSON.stringify(["apple", "orange", "banana"]));

// If array exists in sessionStorage, use it to get random item and empty it from array
} else {

  //get random index of item to removevar randomIndex = Math.floor(Math.random() * myArray.length);

  //remove the item at that index
  myArray.splice(randomIndex, 1); //this returns an array containing the removed item, so you can capture it if you like
}

Post a Comment for "Select Random Item From Array & Remove It, Restart Once Array Is Empty"