kaoscify
kaoscify

Reputation: 1763

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, the process needs to restart. I'm trying to do this using sessionStorage because I need to keep track of which random item gets selected.

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

// If array does not exist in sessionStorage, set it
if (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 {
  var randomItem = myArray[Math.floor(Math.random() * myArray.length)];
  console.log(randomItem);
  console.log(myArray.splice(randomItem, 1));
}

My JSFiddle can be seen here.

Edit: Updated my work here. Eventually the array is cleared out and restarts.

Upvotes: 1

Views: 1044

Answers (2)

JonSG
JonSG

Reputation: 13232

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"]);

Upvotes: 2

Duly Kinsky
Duly Kinsky

Reputation: 996

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 it
if (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 remove
  var 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
}

Upvotes: 1

Related Questions