Sorting An Array Containing Json Elements With Specific Key In The Json Using Javascript

- - JavaScript, Tutorials, Web

Example of sorting an array containing json elements

The following function takes two parameter. The prior one expects an array with json elements within it while the later one expects a string i.e the key member of the json on whose basis the array is supposed to be sorted. For this example we would use “first_name” as the key for the basis of sorting. We use .toUpperCase() method to avoid the sorting based upon the small and big alphabetical letters.

We define a variable personal_infromations which holds an array of jsons. We alert the value stored in it  so that the proof of sorting being done is seen clearly. We store the value returned from sortByKey method to a variable sorted_personal_informations. Now when alerting the value, we see that the json has been sorted based upon the key “first_name”.

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key].toUpperCase();
        var y = b[key].toUpperCase();
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}
var personal_informations = [{"first_name":"Bhishan","last_name":"Bhandari","email":"bbhishan@gmail.com","country":"Nepal","phone_number":"9849060230"},{"first_name":"Ankit","last_name":"Pradhan","email":"ankit@ankit.com","country":"Nepal","phone_number":"9999999999"}, {"first_name":"Aalok","last_name":"Koirala","email":"aalok@aalok.com","country":"Nepal","phone_number":"8888888888"}, {"first_name":"Subigya","last_name":"Nepal","email":"subigya@subigya.com","country":"USA","phone_number":"6666666666"}];

alert(personal_informations);

var sorted_personal_informations = sortByKey(personal_informations, "first_name");

alert(sorted_personal_informations);

Bhishan Bhandari [22] Brewing contents directly from the Himalayas of Nepal. I am a hobbyist programmer and enjoy writing scripts for automation. If you'd like a process to be automated through programming, I also sell my services at Fiverr . Lately, I like to refresh my Quora feeds. Shoot me messages at bbhishan@gmail.com  

Leave a Reply

Your email address will not be published. Required fields are marked *