How do I get a random element of an array that is not null?
Let's say I have an array let arr = [null, null, null, null, null, null, null, null, null]
containing 9 elements.
And I have 9 <button data-index>
, each of which has from data-index=0
todata-index=9
If I click a button, say <button data-index=4>
then we assign the 'Cookie'
corresponding index to arr:arr[4] = 'Cookie'
arr becomes [null, null, null, null, 'Cookie', null, null, null, null]
How can I select a random item / index arr
that null
is not selected arr[4]
since it already contains Cookie
?.
This is for a tick-tock AI game movement.
source to share
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);
source to share