how to get random element of array which is not null?

Viewed 709

Let's say i haven an array of let arr = [null, null, null, null, null, null, null, null, null] containing 9 items.

And i have 9 <button data-index> with each having an data-index=0 to data-index=9

If i click a button, let's say <button data-index=4>, then we assign 'Cookie' to the corresponding index of arr: arr[4] = 'Cookie'

arr becomes [null, null, null, null, 'Cookie', null, null, null, null]

How can i select a random element/index of arr which is null without it selecting arr[4] since it already contains Cookie?.

It's for the AI move of a tic-tac-toe game.

4 Answers
Related