Sort an array so that null values always come last

前端 未结 8 2271
轮回少年
轮回少年 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:34

    like this, note: this will only push the null's to the back

    var arr = ["a", null, "b"];
    var arrSor = [];
    arr.forEach(function (el) {
    
        if (el === null) {
            arrSor.push(el);
        } else {
            arrSor.unshift(el);
        }
    });
    

提交回复
热议问题