Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a JSON object by two keys?

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.

like image 439
Scott Chantry Avatar asked Jul 12 '10 16:07

Scott Chantry


People also ask

How JSON keys are ordered?

The JSON standard defines objects as "an unordered collection of zero or more name/value pairs". As such, an implementation does not need to preserve any specific order of object keys.

Can you assume the order of keys in an object JSON?

Yes, the order of elements in JSON arrays is preserved.

How do I sort object keys?

To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.


1 Answers

Here is a generic way to sort an array of objects, with multiple columns:

var arr = [
    { id:5, name:"Name3" },
    { id:4, name:"Name1" },
    { id:6, name:"Name2" },
    { id:3, name:"Name2" }
],

// generic comparison function
cmp = function(x, y){
    return x > y ? 1 : x < y ? -1 : 0; 
};

//sort name ascending then id descending
arr.sort(function(a, b){
    //note the minus before -cmp, for descending order
    return cmp( 
        [cmp(a.name, b.name), -cmp(a.id, b.id)], 
        [cmp(b.name, a.name), -cmp(b.id, a.id)]
    );
});

To add other columns to sort on, you can add other items in the array comparison.

arr.sort(function(a, b){
    return cmp( 
        [cmp(a.name, b.name), -cmp(a.id, b.id), cmp(a.other, b.other), ...], 
        [cmp(b.name, a.name), -cmp(b.id, a.id), cmp(b.other, a.other), ...]
    );
});

EDIT: per @PhilipZ comment below, the array comparison in JS convert them in strings separated by comas.

like image 144
Mic Avatar answered Oct 06 '22 08:10

Mic