简体   繁体   English

Javascript排序方法处理空值

[英]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/ 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: 您可以在comp函数内部处理null值:

    arrToSort.sort(function (a, b) {
         if (a[strObjParamToSortBy]==null) return 1
         if (b[strObjParamToSortBy]==null) return 0
        return a[strObjParamToSortBy] > b[strObjParamToSortBy];
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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