Javascript sort method handling null values

后端 未结 1 1444
盖世英雄少女心
盖世英雄少女心 2020-12-20 20:26

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

相关标签:
1条回答
  • 2020-12-20 21:01

    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];
        });
    
    0 讨论(0)
提交回复
热议问题