0

I have an array with 10 elements and I pick random 6 elements out of these in an other array on window load. I don't want to keep the position of any element in the new array to be same as previous on page refresh. How should I do that?

var tempArray = [1,2,3,4,5,6,7,8,9,10]; //inital array with 10 elements
var newArray = []; //array where random 6 elements will be pushed from tempArray
//randomize function
function randomNoRepeats(array) {
      var copy = array.slice(0);
      return function() {
        if (copy.length < 1) { copy = array.slice(0); }
        var index = Math.floor(Math.random() * copy.length);
        var item = copy[index];
        copy.splice(index, 1);
        return item;
      };
    };
var chooser = randomNoRepeats(tempArray);
for(var i=1; i<7; i++){
    newArray.push(chooser());
}
newArray = [4,7,9,2,10,1] //Suppose I get this as newArray
newArray = [2,1,5,8,10,3] //On refresh suppose 10 occurs at the same position as previous. Need to avoid this.

Thanks in advance for the help.

Gaurav Prabhu
  • 102
  • 1
  • 9

1 Answers1

0

You have to store your tempArray in your localStorage like this and call your function.

var localArray = localStorage.getItem('tempArray');
if (localArray == null) {
    localStorage.setItem('tempArray', JSON.stringify(tempArray));
    localArray = tempArray;
} else {
    localArray = JSON.stringify(localArray)
}
randomNoRepeats(localArray);

Call to CheckRandom() function after end of your randomNoRepeats() function;

function CheckRandom() {
    for (var i = 0,
            var max = newArray.length; i < max; i++) {
        if (newArray[i] == localArray[i]) {
            randomNoRepeats(localArray);
        }
    }
    localStorage.setItem('tempArray', JSON.stringify(newArray));
}
Sumeet Roy
  • 140
  • 12
  • aren't you comparing an array of 10 elements with an array of 6 elements whereas I need to compare 6 with 6? Like you're storing tempArray in localArray which has 10 elements and then comparing localArray with newArray which has 6 elements? – Gaurav Prabhu Mar 16 '17 at 13:44