Sort an array so that null values always come last

前端 未结 8 2270
轮回少年
轮回少年 2020-11-28 05:46

I need to sort an array of strings, but I need it so that null is always last. For example, the array:

var arr = [a, b, null, d, null]

When

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 06:38

    Use a custom compare function that discriminates against null values:

    arr.sort(function(a, b) {
        return (a===null)-(b===null) || +(a>b)||-(a

    For descending order, just swap a and b in the direct comparison:

    arr.sort(function(a, b) {
        return (a===null)-(b===null) || -(a>b)||+(a

提交回复
热议问题