JavaScript has a native Sort method which can be used to sort arrays. However based on the nature of the array , the implementation varies.
- data=["a","z","c","w","j"];
- alert (data.sort( ));
The above sort method would sort the array without any issues as it is an array of string elements.
JSON return type is an array of objects. Hence sort method cannot be used directly to sort the array. However we can use a comparer function as the argument of the ‘sort’ method to get the sorting implemented.
Comparer function has the following format:
- function compare(a, b) {
- if (a is less than b by some ordering criterion) {
- return -1;
- }
- if (a is greater than b by the ordering criterion) {
- return 1;
- }
-
- return 0;
- }
Return value from the comparer function basically identifies the sort order of subsequent array elements. Summarized as the following:
- If ComparingFunction(a, b) is < 0, then a will be sorted to a lower index than b. Thus a will come first.
- If ComparingFunction (a, b) returns 0, then a and b will retain their respective positions. There won’t be any change in sort order.
- If ComparingFunction (a, b) is > then 0, then b will be sorted to a lower index than a. Thus b will come first.
The comparer function can be called to sort the JSON array as below:
- var array = [{
- "EmployeeName": "John",
- "Experience": "12",
- "Technology": "SharePoint"
- }, {
- "EmployeeName": "Charles",
- "Experience": "9",
- "Technology": "ASP.NET"
- }, {
- "EmployeeName": "Jo",
- "Experience": "3",
- "Technology": "JAVA"
- }, {
- "EmployeeName": "Daine",
- "Experience": "7",
- "Technology": "Sql Server"
- }, {
- "EmployeeName": "Zain",
- "Experience": "6",
- "Technology": "C#"
- }];
-
- function GetSortOrder(prop) {
- return function(a, b) {
- if (a[prop] > b[prop]) {
- return 1;
- } else if (a[prop] < b[prop]) {
- return -1;
- }
- return 0;
- }
- }
-
- array.sort(GetSortOrder("EmployeeName"));
- document.write("Sorted Employee Names : ");
- for (var item in array) {
- document.write("<br>" + array[item].EmployeeName);
- }
-
- array.sort(GetSortOrder("Technology"));
- document.write("<br><br> Sorted Technology Names : ");
- for (var item in array) {
- document.write("<br>" + array[item].Technology);
- }
Output
Sorted Employee Names:
Charles
Daine
Jo
John
Zain Sorted Technology Names:
ASP.NET
C#
JAVA
SharePoint
Sql Server This helper method comes in handy when AJAX calls return JSON array which has to be sorted and dynamically bound to the html DOM for end user display.
You can play around with the
JSFiddle I have created here for better understanding.
Reference