简体   繁体   中英

Javascript sort method handling null values

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];
        });
    }
}

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];
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM