0
idsArr = [ "id12345", "id27891", "id98654"]
idsNameIntvalueArr = [["id22913", "Peter Parker", 15], ["id12345", "Donald Duck", 6], ["id98654", "Mickey Mouse", 9], ["id112233", "Lion King", 9]]

I'm new in Swift, please give me advice, what is the best practice to compare this 2 arrays by id, if id matches, need to make new array with "name" and Int value, in this case:

resultArr = [["Donald Duck", 6],["Mickey Mouse", 9]]

Thanks.

2
  • FYI - it's a really poor design to use an array to hold a collection of data. You should declare a struct that has the three properties of id, name, and value. Then use an array of those struct. Commented Jul 15, 2017 at 17:04
  • Thanks for advice! Commented Jul 15, 2017 at 17:40

1 Answer 1

1

You can do that like this:

let resultArr = idsNameIntvalueArr.filter({ idsArr.contains($0[0] as! String) }).map({ [$0[1], $0[2]] })

First, you need to filter the array to include only the members whose IDs exists in idsArr.

Then, after filtering the array you need to create sub-arrays that contains only the name and age, and this is what map does.

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

2 Comments

You're welcome, and it's important to take @rmaddy advice seriously, good luck.
It‘s my first time using Swift Arrays, too. I do have two Arrays of Strings (myArray1 and myArray2) and need (1) a myResultArray1, that holds only Strings that are present in both Arrays (myArray1 and myArray2), in the same order like myArray1 (of course minus the missing strings that are not included in both arrays) - and (2) a second myResultArray2, that holds the strings only available in myArray2 (which essentially is: myArray2 - myResultArray1). Do you do this with .filter or is there another API on Array for doing what I intend to do?

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.