Sort an array so that null values always come last

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

    Check out .sort() and do it with custom sorting. Example

    function alphabetically(ascending) {
    
      return function (a, b) {
    
        // equal items sort equally
        if (a === b) {
            return 0;
        }
        // nulls sort after anything else
        else if (a === null) {
            return 1;
        }
        else if (b === null) {
            return -1;
        }
        // otherwise, if we're ascending, lowest sorts first
        else if (ascending) {
            return a < b ? -1 : 1;
        }
        // if descending, highest sorts first
        else { 
            return a < b ? 1 : -1;
        }
    
      };
    
    }
    
    var arr = [null, 'a', 'b', null, 'd'];
    
    console.log(arr.sort(alphabetically(true)));
    console.log(arr.sort(alphabetically(false)));

提交回复
热议问题