I have a JSON object that I want to sort by one key first, then by a second key similar to ordering by two columns in SQL. Here is a sample of the JSON I would have:
{
"GROUPID":3169675,
"LASTNAME":"Chantry"
}
I would like to order all the results by the GROUPID and then by LASTNAME. I’ve used the JSON sort function to sort by one key but not multiple.
Any help would be great.
Assuming you have an array of objects:
You can use a custom comparator to do the sorting. To sort first by
GROUPID, and then byLASTNAME, the logic to compare two objects would be:To sort the object array, use the above algorithm and call the sort method on the array. After sorting is done,
datashould have the elements in required sorted order.Here’s another very similar question I answered recently. It’s regarding sorting on multiple columns using jQuery, but you can strip out the jQuery part easily. It presents some customizable approaches which can extend to multiple columns.