0

I'm attempting to sort this JSON object:

JSONObject = {
    "command": [{
        "geobox": [...],
        "jobName": "...",
        "keywords": ["..."],
        "users": ["..."]
    }, {
        "geobox": [...],
        "jobName": "...",
        "keywords": ["...", "..."],
        "users": ["...", "...", "..."]
    }],
    "type": "..."
}

It has "command" which is an array of nested json objects and "type" which I don't really care about. I want it to sort the array of nested json objects in "command" in alphabetical order based on the jobName value. I tried something like this but it didn't work.

JSONObject.command.sort(function (a, b) {
    return JSONObject.command[a].jobName - JSONObject.command[b].jobName
});
Colin Brock
  • 21,267
  • 9
  • 46
  • 61
John Marston
  • 131
  • 1
  • 2
  • 15

1 Answers1

3
var compareStr = function (a, b) { 
   if (a.jobName == b.jobName) 
       return 0; 
   if (a.jobName > b.jobName) 
       return 1; 
   return -1;
};
JSONObject.command.sort(compareStr);
Paolo del Mundo
  • 2,121
  • 13
  • 18
  • This does compile and run and my page does call my function that uses this sorting method, but when I try it out it doesn't appear to sort right. When i call the JSONObject again it appears to be in the same order, which wasn't alphabetical to start with. – John Marston Jul 19 '12 at 18:32