简体   繁体   中英

How to sort array of dictionary by key?

I am trying to sort array of dictionary but not able to do it.

JSON Array: [{"2": "5"}, {"0": "1"}, {"1": "3"}, {"3": "6"}]

Expected Array : [{"0": "1"},{"1": "3"},{"2": "5"},{"3": "6"}]

I am trying this but not able to get expected result.

print(otpInputView.enteredValues.flatMap({ (dic) in
            return dic.keys.sorted()
        })

I am looking forward higher order functions output. (Manually I can achieve this)

Your code is sorting the dictionaries keys, but what you should do is sort the array , by the single dictionary key present. As you can see, the dictionaries in the output array are rearranged, which is why you should sort the array, not the dictionaries.

otpInputView.enteredValues.sorted {
    ...
}

Now we have the dictionaries $0 and $1 , and we want to compare their single key (assuming all dictionaries have exactly one key). We can do that by:

otpInputView.enteredValues.sorted {
    $0.keys.first! < $1.keys.first!
}

This sorts the keys by lexicographical order. The keys appear to all be numbers. If this is the case, and if you want them to be in numerical number, parse them to Int s first:

otpInputView.enteredValues.sorted {
    Int($0.keys.first!)! < Int($1.keys.first!)!
}

I'm using a lot of ! here as I'm making many assumptions about the keys of the dictionary. Unwrap those optionals safely and fall back on default values if you can't make those assumptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM