Sort an array so that null values always come last

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
    if (a === null) {
        return 1;
    }
    if (b === null) {
        return -1;
    }

    // otherwise, if we're ascending, lowest sorts first
    if (ascending) {
        return a < b ? -1 : 1;
    }

    // if descending, highest sorts first
    return a < b ? 1 : -1;
  };
}



var arr = [null, "a", "z", null, "b"];

console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));

Use a custom compare function that discriminates against null values:

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

For descending order of the non-null values, just swap a and b in the direct comparison:

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

Tags:

Javascript