samedi 15 août 2020

Substitute random items in a Javascript array

In Javascript, am trying to randomly substitute half (in this case, 3 out of 6) of the items from an array with different ones (all of the same type), and I need the original items' position to be kept. So for instance, if I have:

var my_array = [a, b, c, d, e, f]

I would want to select three random ones to be substituted with a 0, while the others to keep their initial position. So let's say a, c, and d are the ones the random selector will make go away on one instance, then my array would become:

my_array = [0, b, 0, 0, e, f]

On a different run, the random selector would perhaps pick b, c, and f and so I'd have:

my_array = [a, 0, 0, d, e, 0]

And so on. Thank you so much for your help!




Aucun commentaire:

Enregistrer un commentaire