Phaser.Math.RND.pick from array

I have an array of 10 items, I’m trying to randomly pick items from this array, but only from the first 4 items. Is there a way to do this with Phaser.Math.RND.pick?

Something like Phaser.Math.RND.pick(myArray[0,1,2,3])

I think you could try to slice your array :
Phaser.Math.RND.pick(myArray.slice(0,4))
though you could also do it directly without slicing by using a different function like:
myArray[Phaser.Math.RND.between(0,4)]

I should have added, that I also don’t want to select an item twice, I have been able to splice an item out, but that ruins my loop because the position of the item is changing, deleting an item gives me undefined and I can’t seem to do an if statement to skip over undefined items like if (myarray != undefined) Phaser.Math.RND.pick(myArray.slice(0,4)) just gives me the error of myarray[i] is undefined.

When you are removing the items, you don’t want to just use delete on them because that will leave undefined elements in your array that will cause problems. You need to actually splice() them out and make the array shorter.

In this case, I don’t think pick() will work for you, because you are going to need to know which index was chosen so you can splice() it out. I think you will need to generate a random index (initially with a max value of 4), get the value from the array at that index, splice that index out of the array, and then decrement the max number down so on the next go around you are choosing a random number with a max of 3, and so on. That should work for this purpose.

Best of luck!

1 Like