Sorting JSON Array
There could be a situation where we need to sort the given complex JSON Array object based on the available column/properties.
Following is the sample code which demonstrates how can we achieve this.
Let’s assume following is our JSON Array containing basic Employee names need to sort.
var JsonEmployeeArr = [ { "EmployeeID": 29, "Name": "Sai K"}, { "EmployeeID": 24, "Name": "Balaraju"}, { "EmployeeID": 12, "Name": "Monish B"}, { "EmployeeID": 01, "Name": "Siva T"}];
Following are the core method which will sort based on given property/column in the calling JSON Array (in our case JsonEmployeeArr).
function JSONSort(prop) { return function (a, b) { if (a[prop] > b[prop]) { return 1; } else if (a[prop] < b[prop]) { return -1; } return 0; } }
Now, we are done with major work and ready to see it in live action as follows.
Var sortedArray = JsonEmployeeArr.sort(JSONSort("Name"));
As you can observe, we are overriding the default functionality of the JavaScript and injecting our own method as sort functionality.
Following is the complete code
<script> function JSONSort(prop) { return function (a, b) { if (a[prop] > b[prop]) { return 1; } else if (a[prop] < b[prop]) { return -1; } return 0; } } $(function(){ var JsonEmployeeArr = [ { "EmployeeID": 29, "Name": "Sai K"}, { "EmployeeID": 24, "Name": "Balaraju"}, { "EmployeeID": 12, "Name": "Monish B"}, { "EmployeeID": 01, "Name": "Siva T"}]; Var sortedArray = JsonEmployeeArr.sort(JSONSort("Name")); SortedArray.forEach((functionitem, index){ $("<li>").text(item).appendTo("#sortedUL"); }); }); </script>
Hope it will help you.
Happy Coding. 🙂