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.

+3


source to share


4 answers


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

Run codeHide result


+3


source


Shuffle the fishermen to randomize the array indices and then select them one by one.



The idea is to set a random index on the buttons at the beginning. And don't compute a random index on click.

+2


source


var randomIndex = 0;
while ( arr[randomIndex] != null ) {
    randomIndex = Math.floor( Math.random() * (arr.length - 1) );
}

      

Let me know if it helps.

+2


source


Another solution:

var arr = [null, null, null, null, 'Cookie', null, null, null, null];
var indexes = [];
for (var i =0; i<arr.length; i++){
    if(arr[i] == null)
        indexes.push(i);
}
var index = indexes[parseInt(Math.random() * (indexes.length - 1))];

alert(index);

      

+1


source







All Articles