Remove an Option From a Random Selection Array in JavaScript

October 2025

I'm working on a site for Weird Web October. The idea runs on an infinite loop where each iteration picks a random item from an array of possibilities. But, I don't want the same item picked twice in a row.

This is the function I'm using to make that happen.

JavaScript
function randMinusItem(array, item) {
  const index = array.indexOf(item);
  const items = index > -1 
    ? array.toSpliced(index, 1)
    : array
  return items[
    Math.floor(Math.random() * items.length)
  ]
}

It takes an array and an item. If the item is in the array, then a new array is generated with the item removed. The new item is picked randomly from that array.

If the item isn't in the list, the new item is picked from the entirety of the original array.

Multi Item Example

Here's the function in action with an array of five items.

Output

waiting

HTML

<bitty-1-3 data-connect="Example1">
  <button data-send="update">
    Update From Five Items
  </button>
  <div data-receive="update">
    waiting
  </div>
</bitty-1-3>
JavaScript
window.Example1 = class {
  bittyInit() {
    this.data = [ 
      "alfa", "bravo", "charlie", "delta", "echo"
    ];
  }
  update(_event, el) {
    this.item = randMinusItem(
      this.data, this.item
    );
    el.innerHTML = this.item;
  }
}

Just Two Items

And to give a tighter demo, here's an array with two items. Because, the function won't return the same item twice in a row, clicking the button effectively toggles between them.

Output

waiting

HTML

<bitty-1-3 data-connect="Example2">
  <button data-send="update">
    Update From Two Items
  </button>
  <div data-receive="update">
    waiting
  </div>
</bitty-1-3>
JavaScript
window.Example2 = class {
  bittyInit() {
    this.data = [ "alfa", "bravo" ];
  }
  update(_event, el) {
    this.item = randMinusItem(
      this.data, this.item
    );
    el.innerHTML = this.item;
  }
}
end of line

Endnotes

Note that the this.item isn't defined before the first time it's sent to the randMinusItem() function in the examples. This isn't a problem since an explicit check is done to see if the item is in the array.

I'm using bitty for the examples. It's the web component that wires up the signals between the HTML and JavaScript. Check it out if you're into that kinda thing.