3

I have two arrays:

let arr1 = ["one.json", "two.json", "three.json"]
let arr2 = ["one.json", "three.json"]

Now I want to remove all values of arr2 in arr1, so my expected result in the example above would be let arrFiltered = ["two.json"]. I know how to handle this using a for-loop, however, I thought there may is an easier and more performance-oriented solution?

1
  • for loop is the fastest solution. Commented Oct 17, 2015 at 9:31

2 Answers 2

5

You have to use Set instead of Array in this case.

let arr1 = Set(["one.json", "two.json", "three.json"])
let arr2 = Set(["one.json", "three.json"])

arr1.subtract(arr2)

Fundamental Set Operations

The illustration below depicts two sets–a and b– with the results of various set operations represented by the shaded regions.

enter image description here

  • Use the intersect(_:) method to create a new set with only the values common to both sets.
  • Use the exclusiveOr(_:) method to create a new set with values in either set, but not both.
  • Use the union(_:) method to create a new set with all of the values in both sets.
  • Use the subtract(_:) method to create a new set with values not in the specified set.

Read more

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

Comments

5

Solution using the filter function

let arr1 = ["one.json", "two.json", "three.json"]
let arr2 = ["one.json", "three.json"]

let arrFiltered = arr1.filter{ !arr2.contains($0) }

1 Comment

Strongly suggest this solution: everyone needs to learn filter anyway.

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.