Sort an array so that null values always come last

前端 未结 8 2273
轮回少年
轮回少年 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条回答
  •  情书的邮戳
    2020-11-28 06:24

    Ascending

    arr.sort((a, b) => (a != null ? a : Infinity) - (b != null ? b : Infinity))
    

    Descending

    arr.sort((a, b) => (b != null ? b : -Infinity) - (a != null ? a : -Infinity))
    

    (For descending order if you don't have negative values in the array, I recommend to use 0 instead of -Infinity)

提交回复
热议问题