I am randomly selecting values from an array. I want to be sure that the next selected value is not the same as the current one. How can I implement this rule in Javascript?
const pages = [1, 2, 3, 4, 5];
const random = Math.floor(Math.random() * pages.length);
console.log(pages[random]);
CodePudding user response:
Shuffle the array to guarantee that no number will be repeated:
const pages = [1, 2, 3, 4, 5];
function shuffle(array) {
let currentIndex = array.length, randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
let shuffled = pages.slice()
shuffle(shuffled)
console.log(shuffled[0]);
console.log(shuffled[1]);
CodePudding user response:
You could filter pages removing current value and only after that select random element.
CodePudding user response:
If the one you pick is the same as the previous one, pick a new one:
const pages = [1, 2, 3, 4, 5];
const random = Math.floor(Math.random() * pages.length);
console.log(pages[random]);
let random2;
// Pick a new one:
while (random == ( random2 = Math.floor(Math.random() * pages.length)));
This assumes every value in the array is different, so it just cares that the two indexes (random
and random2
) are different.