0

Sample String:

var output = { 
      "myservices":[
         {"name":"oozie", "hostidn": "1", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
         {"name":"oozie", "hostidn": "2", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
         {"name":"oozie", "hostidn": "3", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
         {"name":"oozie", "hostidn": "4", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
         {"name":"oozie", "hostidn": "5", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"},
         {"name":"single-namenode", "hostidn": "2", "details":"failed process health monitor....", "currstatus":"Warning", "currstatusclass":"warning"}
]};

My Cracker Jack Attempt at doing it.

function sortJSONresultsByHost(a,b)
{
    var objectIDA = parseInt(a.hostidn, 10)
    var objectIDB = parseInt(b.hostidn, 10)
    if(objectIDA === objectIDB)
    {
        return 0;
    }
    return objectIDA > objectIDB ? 1 : -1;
}
output.myservices.sort(sortJSONresultsByHost);

I actually need to figure out how to sort this various ways. Such as by hostidn, by name, by currstatusclass. But I can't figure out the best way to do it. Is there a way to make a function that could do any by choice or would I need to make a set of functions based on which i want to do, if either how? mine above is not working out for me.

1 Answer 1

3
function sortObjectsByKey(objects, key){
    objects.sort(function() {
        return function(a, b){
            var objectIDA = a[key];
            var objectIDB = b[key];
            if (objectIDA === objectIDB) {
                return 0;
            }
            return objectIDA > objectIDB ? 1 : -1;        
        };
    }());
}

sortObjectsByKey(output.myservices, "hostidn");
console.log(output.myservices);
Sign up to request clarification or add additional context in comments.

1 Comment

dont suppose on a different subject with the same object data you would know how I could get the highest hostidn value would you?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.