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)));

Leave a Comment