【问题标题】:Sorting multidimensional Array by its Child's value按子项的值对多维数组进行排序
【发布时间】:2017-02-17 04:22:45
【问题描述】:

我是 Swift 新手,在对多维数组进行排序时遇到困难。 (Alamofire 和 SwiftyJSON 已安装并导入)

我想按每个人的最高分对主 JSON 数组进行排序。 我能够对每个 ["scores"] 进行排序

     for x in 0..<JSONArray.count{
     let b  = JSONArray[x]["scores"].array?.sorted{$0["test"] < $1["test"]}
      }         

但是,我不知道如何影响主要的 JSON 数组顺序。

这是我的 JSON 文件,

{"students": [{
    "id": 1,
    "profile": [{
        "name": "Kenneth",
        "age": 19
    }],
    "scores": [{
        "test": 62
    }, {
        "test": 80
    }, {
        "test": 95
    }]
}, {
    "id": 2,
    "profile": [{
        "name": "Thomas",
        "age": 12
    }],
    "scores": [{
        "test": 60
    }, {
        "test": 92
    }, {
        "test": 30
    }]
}, {
    "id": 3,
    "profile": [{
        "name": "May",
        "age": 15
    }],
    "scores": [{
        "test": 62
    }, {
        "test": 72
    }, {
        "test": 100
    }]
}]}

我想要的最终 JSON 输出是

{"students": [{
    "id": 3,
    "profile": [{
        "name": "May",
        "age": 15
    }],
    "scores": [{
        "test": 100
    }, {
        "test": 72
    }, {
        "test": 62
    }]
}, {
    "id": 1,
    "profile": [{
        "name": "Kenneth",
        "age": 19
    }],
    "scores": [{
        "test": 95
    }, {
        "test": 80
    }, {
        "test": 62
    }]
}, {
    "id": 2,
    "profile": [{
        "name": "Thomas",
        "age": 12
    }],
    "scores": [{
        "test": 92
    }, {
        "test": 60
    }, {
        "test": 30
    }]
}]}

感谢您的帮助!

【问题讨论】:

  • 给我们一个实际的 Swift 测试用例。我们不想浪费时间将您的 JSON 格式化为有效的 Swift。
  • 感谢您的建议。这是我在stackoverflow上提出问题的第一篇文章......并且不知道如何巧妙地提出我的问题......我下次会改进:)

标签: arrays json swift sorting swifty-json


【解决方案1】:

目前您正在对scores 数组进行升序排序,您需要将其排序为降序,然后将此排序数组设置在主 json 数组中。之后使用scores 数组的第一个值对主数组进行排序。

//Forst soret main json by max score
var jsonArray = json["students"].arrayValue

//Sort score array
for x in 0..<jsonArray.count{
    let sortedScores  = jsonArray[x]["scores"].arrayValue.sorted{$0["test"] > $1["test"]}
    jsonArray[x]["scores"] = JSON(sortedScores)
}

//Sort main array using first object of scores array
let sortedJSON = jsonArray.sorted { $0["scores"].arrayValue[0]["test"].intValue > $1["scores"].arrayValue[0]["test"].intValue }

print(sortedJSON)

【讨论】:

  • 嘿尼拉夫,谢谢你的帮助!它完美地工作!我不知道我可以用这种方式“jsonArray[x]["scores"] = JSON(sortedScores)”来更新表格。
  • @Superpotato 欢迎朋友 :)
  • @Superpotato 如果我的解决方案有效,请接受我的回答。如果您不知道如何在 StackOverflow 上接受答案,请查看此链接 meta.stackexchange.com/a/5235/346600
猜你喜欢
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 2011-05-29
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
相关资源
最近更新 更多