This page looks best with JavaScript enabled

Filter before you sort arrays in Javascript

 ·   ·  ☕ 1 min read

Array sorting is easy, but can yield unexpected results if you are not careful.

Consider this example -

1
2
3
const nums = [5, 2, 7, 9];
console.log(nums.sort());
// [ 2, 5, 7, 9 ]

All beautiful and compliant so far.

But, what if Loki lurks his head?

1
const nums = [5, 2, undefined, 7, null, 9];

This problem occurs all the time since you are receiving arrays from external systems, from other libraries, or from code written by your “best friends” (quote intended).

Arrays can now turn up results like this..

1
2
console.log(nums.sort());
// [ 2, 5, 7, 9, null, undefined ]

Best way to avoid surprises? Filter.

1
2
3
4
const nums = [5, 2, undefined, 7, null, 9];
const filterNums = nums.filter(val => !!val);
console.log(filterNums.sort());
// [ 2, 5, 7, 9 ]

I am just returning the truthy value of val to ensure we filter our null, undefined etc.

Your mileage may vary and you may have to change tactics depending on the type of array you get and how you process it after sort.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things