16 January 2013

How to Sort Json Array in Chrome and Opera?

Last week while working on some bug in a Project, I was badly stuck with some strange issue, that i had never experienced

I had a load drop down value dynamically with new values in alphabetical order, it was working fine in Mozilla and IE but not in Chrome and Opera, the reason being chrome perform it's internal sorting based id value, doesn't matter in which order it is coming from back end, so after a long struggle I finally managed to fix it

Below is the simple to which you will pass Json array and it will return sorted array

function sortJsonObject(response){
    var values = [];
    for(var i in response) {
       values.push({ key: i, value: response[i] });
    return values.sort(function(a, b) { return a.value.localeCompare(b.value); });

Hope this will help you guys