Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal Way to Remove Unique Values from Two Arrays

Tags:

swift

I have two arrays of [PFObjects].

For example (simplified):

arr1: [PFObject] = [1, 2, 3, 4, 5, 6, 7, 8]

arr2: [PFObject] = [1, 2, 3, 4, 5]

What is the optimal way to compare arr1 with arr2 and only keep the duplicates (remove unique values).

So that arr1 looks like:

arr1 = [1, 2, 3, 4, 5]
like image 348
Onichan Avatar asked Dec 01 '25 23:12

Onichan


2 Answers

let array = arr1.filter { arr2.contains($0) }

voilà !

like image 59
Pham Hoan Avatar answered Dec 04 '25 13:12

Pham Hoan


First solution (Looping):

var arr1: [PFObject] = [1, 2, 3, 4, 5, 6, 7, 8]
var arr2: [PFObject] = [1, 2, 3, 4, 5]

var temp: [PFObject] = []

for element in arr1 {
    if contains(arr2, element) {
        temp.append(element)
    }
}

arr1 = temp

You can loop over the first array, check if each element is contained in the array, if it is, you can add it to a temporary array. After looping over every element you can replace the value of the first array with your temporary array.

Second solution (Sets):

var arr1: [PFObject] = [1, 2, 3, 4, 5, 6, 7, 8]
var arr2: [PFObject] = [1, 2, 3, 4, 5]

let set1 = Set(arr1)
let set2 = Set(arr2)

var arr1= Array(set1.intersect(set2))    // [1, 2, 3, 4, 5]

What you do here is:

  • First you create sets from your arrays
  • Then you use the intersect method from sets to determine common elements
  • Finally you transform your set to an array before passing it back to arr1

Of course since you will be using sets, duplicate elements will be lost but I'm guessing that shouldn't be a problem in your case

Third solution (filter):

From the answer of Pham Hoan you can use filters to obtain a subset of arr1, the closure gives you the conditions, here it is that arr2 contains the value you are looking at.

let array = arr1.filter { arr2.contains($0) }

This is obviously the shorter solution in terms of code length.

I do not know which technique would be more efficient if you have very large arrays however.

like image 45
The Tom Avatar answered Dec 04 '25 13:12

The Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!