Vineesh TP
Vineesh TP

Reputation: 7973

How do I compare two array Objects - Swift 4

I have 2 Array of type [Any] - objects of dictionaries
And other array contains other set of objects [Any] (2nd array objects are contains in first array)

I need to find the index of the first array of second array elements

eg: -

let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]

let secondArray = [["key3":64],["key6":68]]

How can I find the firstArray index of secondArray elements

Upvotes: 0

Views: 2890

Answers (2)

Yannick
Yannick

Reputation: 3278

First, you take the keys from your secondArray. Then, you try to find the index of key in your firstArray. Be aware that some values might be nil if the key doesn't exist.

let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68], ["key8": 100]]

let indexes = secondArray
    .map({ $0.first?.key }) //map the values to the keys
    .map({ secondKey -> Int? in
        return firstArray.index(where:
            { $0.first?.key == secondKey } //compare the key from your secondArray to the ones in firstArray
        )
    })

print(indexes) //[Optional(2), Optional(5), nil]

I also added an example case where the result is nil.

Upvotes: 1

Mandeep Kumar
Mandeep Kumar

Reputation: 776

let index = firstArray.index{$0 == secondArray[0]};
print("this value ", index);

will print optional(2) , it is basically 2

Upvotes: 3

Related Questions