WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.