I would like to pick an random element from an array, remove it from the array, and then return the element.
I can use sample
to get an element, index
to find where it is, and then delete_at
to remove it, but is there a better way?
We are required to create a function removeRandom() that takes in the array and recursively removes one random item from the array and simultaneously printing it until the array contains items. This can be done through creating a random number using Math. random() and removing the item at that index using Array.
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.
array.delete_at(rand(array.length))
This seems right, and I guess it works best.
EDIT: This same answer is here: Is there a particular function to retrieve then delete random array element? so I'd go with this :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With