UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.