How to remove an element of a given value from an array in Swift

Swift

Swift Problem Overview


I want to remove all elements of value x from an array that contains x, y and z elements

let arr = ['a', 'b', 'c', 'b']

How can I remove all elements of value 'b' from arr?

Swift Solutions


Solution 1 - Swift

A filter:

 let farray = arr.filter {$0 != "b"} 

Solution 2 - Swift

var array : [String]
array = ["one","two","one"]

let itemToRemove = "one"

while array.contains(itemToRemove) {
    if let itemToRemoveIndex = array.index(of: itemToRemove) {
        array.remove(at: itemToRemoveIndex)
    }
}

print(array)

Works on Swift 3.0.

Solution 3 - Swift

If you need to modify initial array, you can use the function removeAll(where:) that is available in Swift 4.2/Xcode 10:

var arr = ["a", "b", "c", "b"]
arr.removeAll(where: { $0 == "b" })
print(arr) // output is ["a", "c"]

However, if you are using Xcode 9 you can find this function in Xcode9to10Preparation (this library provides implementations of some new functions from Xcode 10).

Solution 4 - Swift

EDITED according to comments:

I like this approach:

var arr = ["a", "b", "c", "b"]

while let idx = arr.index(of:"b") {
    arr.remove(at: idx)
}

Original answer (before editing):

let arr = ['a', 'b', 'c', 'b']

if let idx = arr.index(of:"b") {
    arr.remove(at: idx)
}

Solution 5 - Swift

In Swift 3 I simply do:

arr = arr.filter { $0 != "a" } 

.filter, .sort and .map are great for saving time and solve lots of problems with little code.

This article has good examples and explain the differences and how they work: https://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/

Solution 6 - Swift

A general approach is to exploit first class procedures. (However, this approach is much more powerful than what is required for your question.) To illustrate, say you want to avoid "Justin" repeatedly in many collections.

let avoidJustin = notEqualTester ("Justin")

let arrayOfUsers = // ...

arrayOfUsers.filter (avoidJustin)

let arrayOfFriends = // ...

arrayOfFriends.filter (avoidJustin)

With this, you avoid repeatedly creating a closure each time you want to avoid Justin. Here is notEqualTester which, given a that, returns a function of this that returns this != that.

func notEqualTester<T: Equatable> (that:T) -> ((this:T) -> Bool) {
  return { (this:T) -> Bool in return this != that }
}

The returned closure for this captures the value for that - which can be useful when that is no longer available.

Solution 7 - Swift

If you have more than one element to remove, thanks to first answer.

 var mainArray = ["a", "b", "qw", "qe"]
 let thingsToRemoveArray = ["qw", "b"] 


        for k in thingsToRemoveArray {
            mainArray =  mainArray.filter {$0 != k}
          }
     

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEncore PTLView Question on Stackoverflow
Solution 1 - SwiftiluvcapraView Answer on Stackoverflow
Solution 2 - SwiftNitrousjpView Answer on Stackoverflow
Solution 3 - SwiftRoman PodymovView Answer on Stackoverflow
Solution 4 - SwiftJensView Answer on Stackoverflow
Solution 5 - SwiftPaula HasstenteufelView Answer on Stackoverflow
Solution 6 - SwiftGoZonerView Answer on Stackoverflow
Solution 7 - SwiftHopeView Answer on Stackoverflow