jQuery: Sorting JSON by properties
http://stackoverflow.com/questions/881510/#14949429
by Ufuk Ozdemir
JavaScript
var people = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 3 },
{ 'myKey': 'C', 'status': 7 },
{ 'myKey': 'D', 'status': 9 },
{ 'myKey': 'E', 'status': 10 },
{ 'myKey': 'F', 'status': 2 },
{ 'myKey': 'G', 'status': 2 },
{ 'myKey': 'H', 'status': 1 },
{ 'myKey': 'I', 'status': 12 },
{ 'myKey': 'J', 'status': 5 },
{ 'myKey': 'K', 'status': 14 }
];
alert("0. At start: " + JSON.stringify(people));
//META.fn: sortJSON
function sortJSON(data, key) {
return data.sort(function (a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
people2 = sortJSON(people, 'myKey');
alert("1. After sorting (0 to x): " + JSON.stringify(people2));