0

I have an array of objects like:

let food = [apple, orange, peach, pear].

Each object looks something like this:

let apple : Fruit = [
  name: "Apple",
  colors: ["red", "yellow", "green", "orange"]
]

I have another array of strings that the food array should be filtered with:

let avoid = ["red", "yellow"]

I want to create a new array from the food array, with Fruit objects that do not contain any of the colors in the avoid array. So in this case, Apple would not be in the food array because it contains both red and yellow.

Thanks!

2
  • 1
    What does Fruit represent? A type, a protocol, a typealias? something like is not helpful. Commented May 22, 2019 at 7:48
  • 1
    var names start with a lowercase letter. Type names start with an uppercase letter. apple is a var Fruit is a type. :D Commented May 22, 2019 at 7:48

2 Answers 2

4

Since you haven't given any definition of Fruit object, I'm considering one for reference.

struct Fruit {
    let name: String
    let colors: [String]
}

Creating the food array,

let apple = Fruit(name: "Apple", colors: ["red", "yellow", "green", "orange"])
let orange = Fruit(name: "Orange", colors: ["red", "green", "orange"])
let peach = Fruit(name: "Peach", colors: ["green", "orange"])
let pear = Fruit(name: "Pear", colors: [ "green"])
let food = [apple, orange, peach, pear]

To filter the food array using avoid array, we can use Set intersection method, i.e.

let avoid = ["red", "yellow"]
let filteredFruits = food.filter { return Set($0.colors).intersection(avoid).isEmpty }
print(filteredFruits.map({ $0.name })) //["Peach", "Pear"]

filteredFruits will contain objects - pear and peach

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

4 Comments

I would make the initial assumption that Fruit is a struct not a class as it has no need to be a class in this example and struct should always be the first choice for types.
This is just an example. As I already said he might have taken it a class too. We aren't sure about that. class and struct always depends upon your use case.
Exactly, which is why struct should be the choice here. Since it is what you would choose for this example if you were writing it. Nothing here needs a class.
Perfect -- this is what I meant :) And yeah, I forgot to give an example of the Fruit object.
0
let res= food.filter(function(fruit) {
  return !fruit.colors.some(r=> avoid.indexOf(r) >= 0)
})

1 Comment

Please, can you extend your answer with more detailed explanation? This will be very useful for understanding. Thank you!

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.