-1

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

This is a result of script. I want to avoid the same values next to each other like in the red circle.

ab4563
  • 9
  • 2

2 Answers2

1

You could filter pages removing current value and only after that select random element.

yjay
  • 942
  • 4
  • 11
1

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.

kmoser
  • 8,780
  • 3
  • 24
  • 40