David Robertson
David Robertson

Reputation: 1581

Filter two arrays Swift

I have one empty array and two arrays with data

var resultsArray = [String]()

var array1 = ["1","2","2","3","4"]
var array2 = ["1","2","2","3","4","5","6"]

My goal is to append the resultsArray with the elements from array2 that don't match array1 ("5" and "6" in the example).

What's the subtlest way to do so?

Thank you.

Upvotes: 2

Views: 11739

Answers (3)

vadian
vadian

Reputation: 285059

Use the filter function

var resultsArray = [String]()

let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]

let filteredArray = array2.filter{ !array1.contains($0) }

resultsArray.appendContentsOf(filteredArray)

If the collections contain unique items consider to use Set rather than Array


Update Swift 5.1:

In iOS 13, macOS 10.15 there is a new API in Array

public func difference<C>(from other: C) -> CollectionDifference<Element> where C : BidirectionalCollection, Self.Element == C.Element


var resultsArray = [String]()

let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]

let diff = array2.difference(from: array1)
resultsArray.append(contentsOf: array1)
for change in diff {
    switch change {
    case .remove(let offset, _, _): resultsArray.remove(at: offset)
    case .insert(let offset, let element, _): resultsArray.insert(element, at: offset)
    }
}

Upvotes: 21

jnblanchard
jnblanchard

Reputation: 1200

var resultsArray: [String] = []

let arrayX = ["1","2","2","3","4"]
let arrayY = ["1","2","2","3","4","5","6","7"]

let setX = Set(arrayX), setY = Set(arrayY)

resultsArray.append(contentsOf: setY.subtracting(setX))

This answer is faster than using filter.

Upvotes: 2

Rahim Khalid
Rahim Khalid

Reputation: 469

Use filter function for the purpose to find the different number of elements in the both array

let Filter = array2.filter{!array1}
resultArray.appendContentsof(Filter)

Upvotes: 0

Related Questions