简体   繁体   中英

Check if position of array elements after randomize is same

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.

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)); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM