Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort method handling null values

Tags:

javascript

I have a list of objects where I want to sort the objects based on a field I know I can use sort methods. When the comparing field have null values, sorting is not happening, how to fix this issue?

http://jsfiddle.net/mailtoshebin/kv8hp/

var arrOfObj = [
    {
        "Name": "Zak",
        "Age": 25
    },
    {
        "Name": "Adel",
        "Age": 38
    },
    {
        "Name": null,
        "Age": 38
    },
    {
        "Name": "Yori",
        "Age": 28
    }
];

sortArrOfObjectsByParam(arrOfObj, "Name");
alert("ASCENDING: " + arrOfObj[0].Name + ", " + arrOfObj[1].Name + ", " + arrOfObj[2].Name);

function sortArrOfObjectsByParam(arrToSort , strObjParamToSortBy  ) {
    if(sortAscending == undefined) sortAscending = true;  // default to true

    if(sortAscending) {
        arrToSort.sort(function (a, b) {

            return a[strObjParamToSortBy] > b[strObjParamToSortBy];
        });
    }
    else {
        arrToSort.sort(function (a, b) {
            return a[strObjParamToSortBy] < b[strObjParamToSortBy];
        });
    }
}
like image 231
Shebin Mathew Avatar asked Nov 15 '13 19:11

Shebin Mathew


People also ask

How do I sort NULL values?

If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.

What is the sort () method?

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.


1 Answers

you can deal with the null values inside the comp func:

    arrToSort.sort(function (a, b) {
         if (a[strObjParamToSortBy]==null) return 1
         if (b[strObjParamToSortBy]==null) return 0
        return a[strObjParamToSortBy] > b[strObjParamToSortBy];
    });
like image 71
user1129360 Avatar answered Oct 20 '22 23:10

user1129360