arrays - 按子级值对多维数组进行排序

标签 arrays json swift sorting swifty-json

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

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

     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
    }]
}]}

感谢您的帮助!

最佳答案

当前您正在按升序对 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)

关于arrays - 按子级值对多维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289349/

相关文章:

jquery - 具有静态 json 数据源的数据表

ios - 为什么我的 Google map 应用程序不打印出点击的坐标?

swift - 将 Xcode8 与使用 cocoapods 的 swift 2.3 项目一起使用

javascript - jQuery - 选择一个仅包含超过一定数量子级的容器

javascript - 如何在jquery/javascript中将对象转换为数组

arrays - 通过本地化改变ImageView的图片

c++ - 在 C++ 中初始化大型二维数组

javascript - 使用单引号和双引号时JSON Key有什么区别吗?

javascript - $.ajax() 和 "Uncaught ReferenceError: data is not defined"

ios - 如何在 JSQMessagesViewController 的帮助下在 swift 4 中实现一种机制,让用户使用 firebase 阻止滥用用户