0

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

2
  • Are you saying that you want find the entire second array as a sub-array of the first array? Your question isn't clear Commented Dec 26, 2017 at 12:03
  • @DuncanC: exactly. second array elements are contains in the first one. Commented Dec 26, 2017 at 12:07

2 Answers 2

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

will print optional(2) , it is basically 2

Sign up to request clarification or add additional context in comments.

1 Comment

It might be better to use the Array.index(where:) of the method so it's clear what you're doing. Using trailing closure syntax makes it hard for readers to know what you're doing.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.