snovakovic / fast-sort

Blazing fast array sorting with TypeScript support.
MIT License
311 stars 30 forks source link

Undefined, null, and empty string values aren't getting sorted properly when using Intl.Collator(). #54

Closed Streudal closed 2 years ago

Streudal commented 2 years ago

I am not sure if this is intended but I came across an issue when trying to create a natural sort algorithm and noticed that the undefined, null, and empty string values get sorted in random orders depending on which value was used. This seems to only be happening with array of objects as far as I know.

I have a CodeSandbox here: https://codesandbox.io/s/fast-sort-issues-4fdkcw?file=/src/App.tsx to kinda show what's going on.

1.) If some of the data has empty strings for the name field then the empty string will be placed at the top or at the bottom depending on sort order. Not the biggest concern because I think this is by design.

2.) If some of the data has undefined or null values then the items will be semi-sorted in the list. The undefined/null values will sometimes be in the middle, on top, on bottom, really close to the bottom, etc. This is the main concern.

snovakovic commented 2 years ago

@Streudal When defining custom comparer fast-sort use that comparer function to determine how to sort on things.. So it's up to you to ensure things are sorted as expected...

Seams like the above described issue is default behavior of Intl.Collator

One way you can fix that is by casting null values to undefined in callback to get property value.

sort(data).asc(r => r[column] || undefined)

BY doing the above the null values will be casted to undefine and things should be sorted as expected.

In your example it will be done as following https://codesandbox.io/s/fast-sort-issues-forked-kfu8q9?file=/src/App.tsx:1574-1977

Hope that helps?

image