Categories
JavaScript Answers

How to sort an array so that null values always come last with JavaScript?

Spread the love

Sometimes, we want to sort an array so that null values always come last with JavaScript.

In this article, we’ll look at how to sort an array so that null values always come last with JavaScript.

How to sort an array so that null values always come last with JavaScript?

To sort an array so that null values always come last with JavaScript, we can use the array sort method.

For instance, we write

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

to call arr.sort with a callback that sorts non-null values in ascending order.

We check if a or b is null.

If they are, we return Infinity as its value and use that for sorting.

To sort in descending order, we flip the expressions in the callback by writing

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

Conclusion

To sort an array so that null values always come last with JavaScript, we can use the array sort method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *