feat: Natural sort collection names with numbers

Sorts collections by name in alphabetical order
Collections with numbers in the names are sorted in numerical order.

Results in `['Test 10', 'Test 2', 'Test 1']`
being sorted to: `['Test 1', 'Test 2', 'Test 10']`
instead of: `['Test 1', 'Test 10', 'Test 2']`

Accurately sorts numbers with decimals as well.
This commit is contained in:
Adam Armistead 2024-11-14 20:04:59 -08:00 committed by GitHub
parent 40001949b8
commit 6b43d9ee53
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -76,15 +76,16 @@ export const collectionsSlice = createSlice({
},
sortCollections: (state, action) => {
state.collectionSortOrder = action.payload.order;
const collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
switch (action.payload.order) {
case 'default':
state.collections = state.collections.sort((a, b) => a.importedAt - b.importedAt);
break;
case 'alphabetical':
state.collections = state.collections.sort((a, b) => a.name.localeCompare(b.name));
state.collections = state.collections.sort((a, b) => collator.compare(a.name, b.name));
break;
case 'reverseAlphabetical':
state.collections = state.collections.sort((a, b) => b.name.localeCompare(a.name));
state.collections = state.collections.sort((a, b) => -collator.compare(a.name, b.name));
break;
}
},