Sorting a complex array¶
First up:
What is a complex array? An array like this. This example contains post comments from an internet forum.
Let's sort it by the users follower count! Sounds complicated? Wrong. Super easy :D
We have this json:¶
[
{
"user_info": {
"username": "Muggenmal",
"joined": 6221326,
"followers": 192
},
"message": "Another one bites de_dust 2",
"like_count": 1993
},
{
"user_info": {
"username": "Bedrull33",
"joined": 432523521,
"followers": 0
},
"message": "Huh, I've only played pubg a couple of times. What do you mean?",
"like_count": 23
},
{
"user_info": {
"username": "icrouch",
"joined": 123656,
"followers": 210
},
"message": "Oh ok that makes a lot more sense. I didn't know there is a TDM mode.",
"like_count": 1993
}
]
Now, how do i sort this darn thing?¶
Quite easily.
Have a look at JSON_ARRAY_SORT_MODE. This enum houses the four sorting modes.
Which are:
- Numeric, Ascending order
- Numeric, Descending order
- Alphabetically, Ascending order
- Alphabetically, Descending order
Because the users follower count is, obviously, an integer, we want to sort numerically. We also want the most-followed user on top, so we also want to sort in descending order.
JSON_ARRAY_SORT_MODE
::NUM_DESC
it is!
C++:¶
// Let's first import the array.
Json json;
json.Parse(aboveJsonCode);
// Now sort it!
// You can provide a key to sort after.
json.AsArray.Sort("user_info.followers", JSON_ARRAY_SORT_MODE::NUM_DESC);
That's it!
If two values cannot be compared
If two values cannot be compared because, for example, their sorting-key cannot be found, they will just be ignored by the sorter.
That will most likely pile them up at either the start or the end of the array.