Hyrule Hyrule - 5 months ago 34
Javascript Question

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

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.

Answer Source

An ES6 solution with filter:

var arr = [null, null, null, null, 'Cookie', null, null, null, null];

var indexes = Array.from(Array(arr.length).keys());
var availableIndexes = indexes.filter((index) => arr[index] == null);
var selectedIndex = availableIndexes[Math.floor(Math.random()* availableIndexes.length)];

console.log(availableIndexes);
console.log(selectedIndex);