gpt4 book ai didi

arrays - 如何根据另一个数组元素属性快速排序数组

转载 作者:行者123 更新时间:2023-11-28 13:58:45 25 4
gpt4 key购买 nike

所以,我有这些数组:

let persons = [{idPerson: 4, name: "John"}, {idPerson: 2, name: "Bill"}, {idPerson: 3, name: "Vivian"}, {idPerson: 1, name: "Max"}]
let positions = [{idPerson: 1, value: 5}, {idPerson: 2, value:6}, {idPerson: 3, value: 7}, {idPerson: 4, value: 8}]

我想根据 positions 数组,按属性 value 对数组 persons 进行排序。

idPerson 是连接两个数组的属性。

最好的方法是什么?

最佳答案

struct PerosonRemote {
var personID: Int
var name: String
}

struct Position {
var personID: Int
var value: Int
}

struct Peroson {
var value: Int
var name: String
}

let personsRemote = [PerosonRemote(personID: 4, name: "John"),
PerosonRemote(personID: 2, name: "Bill"),
PerosonRemote(personID: 3, name: "Vivian"),
PerosonRemote(personID: 1, name: "Max")]

let positionsRemote = [Position(personID: 1, value: 5),
Position(personID: 2, value: 6),
Position(personID: 3, value: 7),
Position(personID: 4, value: 8)]

func getValue(forPersonID id: Int) -> Int {
for position in positionsRemote {
if position.personID == id {
return position.value
}
}

return 0 // Not found PersonID
}


var persons = [Peroson]()

personsRemote.forEach { (person) in
persons.append(Peroson(value: getValue(forPersonID: person.personID), name: person.name))
}

var sortedPersons = persons.sorted { $0.value > $1.value }

print(sortedPersons)

关于arrays - 如何根据另一个数组元素属性快速排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53709953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com