I have the below Json object in jquery which i m using to fill a jquery grid.
Now i need to sort it on the basis of "performanceName".
Please advice how i can achieve this. Please i knw same kinda question is posted 100 times but still i m struggling to implement sorting on below json
{
"callback": "",
"html": "",
"message": [
""
],
"responseData": [
{
"collectionTitleId": 1107861,
"collectionTitleIdSpecified": true,
"performanceField": {
"addedDate": "6/16/2011 11:11:10 PM",
"artist": "Corbis",
"performanceName": "Showcase Graphic 003 - Anime Girl Purple",
"performanceType": "Graphic",
"provider": "DMSP Dynamic Digital"
},
"sortOrder": "01"
},
{
"collectionTitleId": 1113513,
"collectionTitleIdSpecified": true,
"performanceField": {
"addedDate": "5/25/2011 9:27:39 AM",
"artist": "Beloved",
"performanceName": "Hating On Your Feet (Verse)",
"performanceType": "LabelTone",
"provider": "p1"
},
"sortOrder": "02"
}
],
"status": [
"Success"
]
}
Thanks in advance
2 Answers 2
You can use Array.prototype.sort to in-place sort an array. Without any arguments, this attempts to sort elements alphabetically, but you can pass in a comparing function instead. This function receives two arguments and should return less than 0, 0 or greater than 0 to define where argument 1 should be in relation to argument 2.
Your sorting function should look something like this:
data.responseData.sort(function (a, b) {
a = a.performanceField.performanceName,
b = b.performanceField.performanceName;
return a.localeCompare(b);
});
Working demo: http://jsfiddle.net/AndyE/aC5z4/
localeCompare does the hard work of comparing the strings for us.
3 Comments
var people = [
{ 'myKey': 'Ankit', 'status': 0 },
{ 'myKey': 'Bhavik', 'status': 3 },
{ 'myKey': 'Parth', 'status': 7 },
{ 'myKey': 'Amin', 'status': 9 },
{ 'myKey': 'Russ', 'status': 9 },
{ 'myKey': 'Pete', 'status': 10 },
{ 'myKey': 'Ravi', 'status': 2 },
{ 'myKey': 'Tejas', 'status': 2 },
{ 'myKey': 'Dilip', 'status': 1 },
{ 'myKey': 'Piyush', 'status': 12 }
];
alert("0. At start: " + JSON.stringify(people));
//META.fn: sortData
jQuery.fn.sortData = function (prop, asc) {
return this.sort(function (a, b) {
var x = a[prop];
var y = b[prop];
var retrunStatus = ((x < y) ? 1 : ((x > y) ? -1 : 0));
return (asc==undefined || asc) ? (retrunStatus * -1) : retrunStatus ;
});
}
people2 = $(people).sortData('myKey',false);
alert("1. After sorting (0 to x): " + JSON.stringify(people2));