swift - 根据键和值对字典数组进行排序
问题描述
最近一直在玩高阶函数,我想到了一个案例,我不知道这是否可能,考虑下面的案例。
字符串字典-
typealias StringDictionary = [String: String]
var Group: [StringDictionary] = [
["Key1":"val2"],
["Key4":"val4"],
["Key3":"val3"],
["Key5":"val5"],
["Key2":"val1"],
]
我想将这组字典重新排序为这样。
预期结果
var Result = [
["Key1":"val1"],
["Key2":"val2"],
["Key3":"val3"],
["Key4":"val4"],
["Key5":"val5"],
]
使用高阶函数
解决方案
typealias StringDictionary = [String: String]
var Group: [StringDictionary] = [
["Key1":"val2"],
["Key4":"val4"],
["Key3":"val3"],
["Key5":"val5"],
["Key2":"val1"],
]
let keys = Group.map { Array($0.keys) }.reduce([String]()) { $0 + $1 }.sorted()
let values = Group.map { Array($0.values) }.reduce([String]()) { $0 + $1 }.sorted()
let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))
let newGroup:[StringDictionary] = dict.map { [$0:$1] }.sorted{ $0.keys.first! < $1.keys.first! }
print(newGroup)
推荐阅读
- node.js - 我正在尝试使用 React 和 Express 构建联系表单,但它不起作用
- cypress - 赛普拉斯:如何对“烟雾”、“理智”和“回归”等测试进行分组
- android - W/System:忽略标头 X-Firebase-Locale,因为它的值为 null 。通过许多 ans 没有找到 ans
- php - 在 laravel 8 中使用带有 livewire 的多下拉依赖项
- php - 使用机架空间表单帖子的内容类型不正确
- .net - Windows Server 累积更新后与第 3 方应用程序的 web.config 中的 targetFramework 相关的配置错误?
- jira - 向 JIRA 的 API 请求添加自定义字段
- r - R中的Dagitty调整集
- python - 将 django 从 2.4 升级到 3.0 时出现不兼容问题
- javascript - 如果条件:(64 > 360) 为真?