Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 - Filtering Array with Array

I have a list of entries, that have an id, and I want to filter them down to ones that have an entry.id matching one of the ids in selectedIDs. Is there a way to do this with filter or do I have to use a for loop?

struct Entry {
    let id: String
}
var allEntries = [Entry]()
var selectedIDs = [String]

e.g.

allEntries = [Entry(id: "1"), Entry(id:"2"), Entry(id:"3"), Entry(id:"4")]
selectedIDs = ["1", "3"]

// return selectedEntries
var selectedEntries = [Entry(id: "1"), Entry(id: "3")]
like image 414
user3628240 Avatar asked Jan 28 '23 07:01

user3628240


1 Answers

There's nothing wrong with Rakesha Shastri's answer. For performance reasons, you may want to make selectedIDs a Set instead of an Array:

let allEntries = [Entry(id: "1"), Entry(id:"2"), Entry(id:"3"), Entry(id:"4")]
let selectedIDs: Set<String> = ["1", "3"]
let selectedEntries = allEntries.filter({ selectedIDs.contains($0.id) })

The reason is that searching an Array has a computational complexity of O(n) where n is the length of the array, while searching a Set (i.e. a hash table) is O(1) on average.

  • If you keep selectedIDs as array, the overall solution has a complexity of O(n * m) where n and m are the lengths of selectedIDs and allEntries, respectively.

  • If you use Set, the overall complexity reduces to O(m).

Having said that, your example is too trivial for either methods to make a difference.

like image 159
Code Different Avatar answered Feb 04 '23 03:02

Code Different