Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - Filter and sort array of dictionaries, by dictionary values, with values from array

I am trying to implement the following behavior in an elegant way:

Reorder users by the id in userIds and filter out all users whose id isn't in userIds

Trying to do it the "Swifty way":

var users = [["id": 3, "stuff": 2, "test": 3], ["id": 2, "stuff": 2, "test": 3], ["id": 1, "stuff": 2, "test": 3]]
var userIds = [1, 2, 3]

userIds.map({ userId in users[users.index(where: { $0["id"] == userId })!] })

produces the expected result for the reordering and filtering. But the code crashes when userIds contains an id that doesn't belong to a user in users (e.g. 4) thanks to the force-unwrap.

What am I missing to make it work without crashing?

like image 443
Herakleis Avatar asked Dec 23 '22 17:12

Herakleis


2 Answers

var users = [
    ["id": 3, "stuff": 2, "test": 3],
    ["id": 2, "stuff": 2, "test": 3],
    ["id": 1, "stuff": 2, "test": 3]
]
var userIds = [2, 1, 3]

let filteredUsers = userIds.flatMap { id in
    users.first { $0["id"] == id }
}
print(filteredUsers)
like image 140
Alex Shubin Avatar answered May 06 '23 19:05

Alex Shubin


The following works:

let m = userIds.flatMap { userId in users.filter { $0["id"] == userId }.first }

It filters to find the correct member and then "flat"s the resulting array, removing the empty optionals.

like image 40
luk2302 Avatar answered May 06 '23 19:05

luk2302