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

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

Replace userswith id in userIdsand filter out everything userwhose id is not inuserIds

Trying to do this "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 })!] })

gives the expected result for reordering and filtering. But the code falls when userIdscomprises an identifier that does not apply to userin users(for example 4) due to resiliency.

What am I missing to get it working smoothly?

+4
source share
3 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)
+5
source

:

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

It filter, , "" , .

+5

, dublicate ID

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

        let filter = userIds.map {
            id in
            users.filter {
                $0["id"] == id
            }
        }

        print(filter)
0

Source: https://habr.com/ru/post/1677917/


All Articles