最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript sort method handling null values - Stack Overflow

programmeradmin1浏览0评论

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 paring field have null values, sorting is not happening, how to fix this issue?

/

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

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 paring field have null values, sorting is not happening, how to fix this issue?

http://jsfiddle/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];
        });
    }
}
Share Improve this question edited May 18, 2017 at 7:54 Mel 6,07510 gold badges40 silver badges42 bronze badges asked Nov 15, 2013 at 19:24 Shebin MathewShebin Mathew 3181 gold badge7 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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

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

评论列表(0)

  1. 暂无评论