How to check if element of an array is in another array?

4.1k views Asked by At

I have two Array holding the instances of class MYItems. FavoriteItems holds the favorite items from the array Items

var Items :[MYItems] = []
var favoriteItems = [MYItems]()

Now i want to check if the Items array contains the favoriteItems in the . How can i acheive this? i tried using the below Find method

if let index = find(favoriteItems, Items[indexPath.row]){

             println("found item")
   }else{
             println("doesnotcontains item")
        }

I tried using the below but that doesnot help too..

 if contains(favoriteItems, Items[indexPath.row]){

            println("found item")

        }else{

         println("doesnot contain item")

        }

But it always goes to the else block? Why is this happening when i contain one of the items in array for sure.

4

There are 4 answers

2
milo526 On BEST ANSWER

I suspect you are searching for the problem in the wrong place. You code on how to search through the array is indeed correct.

var Items :[Int] = [1,2,3,4,5,6,7,8,9,]
var favoriteItems:[Int] = [1,3,4,5,7]

if contains(Items, favoriteItems[3]){
  println("found item")
}else{
  println("doesnotcontains item")
}

Does work in swift 1.2. The fourth item of favoriteItems (5) is indeed inside Items and it also does print found item

For your use with custom classes, you should make your class Equatable to do so you much make the class conform to the Equatable protocol.

func == (lhs:MyItem, rhs:MyItem) -> Bool{
  return lhs.id == rhs.id
}

class MyItem :Equatable {
  let id:Int
  init(id:Int){
    self.id = id
  }
}

var Items :[MyItem] = [MyItem(id: 1), MyItem(id:2), MyItem(id:4), MyItem(id:5)]
var favoriteItems:[MyItem] = [MyItem(id: 1), MyItem(id:2)]

if contains(Items, favoriteItems[1]){
  println("found item")
}else{
  println("doesnotcontains item")
}
1
Pieter Kuijpers On

Convert the arrays to a Set and then use isSubsetOf:

let itemsSet = Set(Items)
let favoritesSet = Set(favoriteItems)
let result = favoritesSet.isSubsetOf(itemsSet)
1
Rashad On
NSMutableSet *intersection = [NSMutableSet setWithArray:aArray];
[intersection intersectSet:[NSSet setWithArray:bArray]];
NSArray *intrsecArray = [intersection allObjects];

Subset of objects in bArray that are not present in aArray:

NSMutableArray *cArray = [NSMutableArray arrayWithArray:bArray];
[cArray removeObjectsInArray:aArray];
0
Shaik Riyaz On

It's very simple, use the following method of NSArray

id commonObject = [array1 firstObjectCommonWithArray:array2];

Ref: https://developer.apple.com/documentation/foundation/nsarray/1408825-firstobjectcommonwitharray?language=objc