How do I get random element from an array and remove it from there?

Viewed 932

I know there is a function randomElement() that gets random elements and returns it.

var array = ["a", "b", "c", "d", "e"]
var result = array.randomElement()
print(array) //["a", "b", "c", "d", "e"]
print(result) //Optional("c")

So it works pretty well, but all array stays as it is. How can I remove that random element from an array? Is there a quick way without iterating, finding and removing it?

3 Answers

Select a random index rather than a random element.

if let index = array.indices.randomElement() {
    let value = array.remove(at: index)
    // ...
}

See Alexander's comments below if the intention is to remove all the elements. Removing all the elements this way would be O(n^2), and using .shuffled() first would be much faster.

You can try this.

var array = ["a", "b", "c", "d", "e"]
var result = array.randomElement()
if let index = array.firstIndex(of: result ?? "")  {
  array.remove(at: index)
}
print(array) //["a", "b", "c", "d", "e"]
print(result) //Optional("c")
extension Array {
    mutating func removeRandom() -> Element? {
        if let index = indices.randomElement() {
            return remove(at: index)
        }
        return nil
    }
}
Related