Here's a simple unsorted array of JSON objects:


var someArray = [
{
"id": 2,
"name": "gamma"
},
{
"id": 3,
"name": "alpha"
},
{
"id": 1,
"name": "beta"
}
];

And a generic sorting function:


/**
* Generic array sorting
*
* @param property
* @returns {Function}
*/
var sortByProperty = function (property) {
return function (x, y) {
return ((x[property] === y[property]) ? 0 : ((x[property] > y[property]) ? 1 : -1));
};
};

Calling this...


someArray.sort(sortByProperty('id'));

...produces an array sorted by the id property:

[
{
"id": 1,
"name": "beta"
},
{
"id": 2,
"name": "gamma"
},
{
"id": 3,
"name": "alpha"
}
]

Calling this...


someArray.sort(sortByProperty('name'));

...produces an array sorted by the name property:


[
{
"id": 3,
"name": "alpha"
},
{
"id": 1,
"name": "beta"
},
{
"id": 2,
"name": "gamma"
}
]

Simple.