GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Array Filtering

Forums > SwiftUI

Let's say I have an array of objects, like so:

[
  {
  "name": "david",
  "type": "human"
  },
  {
  "name": "chris",
  "type": "human"
  },
  {
  "name": "thor",
  "type": "god"
  },
  {
  "name": "wolverine",
  "type": "mutant"
  }
]

Now I have another array, like so:

["human", "puppy", "automobile"]

How can I get all the objects from the first array that have a type value that exists in the second array?

3      

Assuming the shape of your data object from that JSON:

import Foundation

struct CharacterData {
    let name: String
    let type: String
}

//presumably the data would normally be loaded from some JSON
//but for sake of example I'm just building it manually
let characters: [CharacterData] = [
    CharacterData(name: "David", type: "human"),
    CharacterData(name: "Chris", type: "human"),
    CharacterData(name: "Thor", type: "god"),
    CharacterData(name: "Wolverine", type: "mutant"),
]

let filteredCharacters = characters.filter {
    ["human", "puppy", "automobile"].contains($0.type)
}

print(characters)
print(filteredCharacters)

4      

THANK YOU!

3      

Just a follow-up to say that this is exactly what I needed and works perfectly. Thanks again.

3      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. Unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a FREE crash course.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.