Sorting with support for numbers, dates, unicode and more.
You know this from your file manager:
- Numbers are handled properly – “2” is before “10”
- Strings are after numbers
- Empty strings are after “z”
- “a” is before “B” (opt out via
caseSensitive: true
) - Semver-compatible sorting of version numbers
⏴ ['10. tenth', 'odd', 1, '', '2. second'].sort(naturalSort())
⏵ [1, '2. second', '10. tenth', 'odd', '']
⏴ ['a', 'B'].sort(naturalSort())
⏵ ['a', 'B']
⏴ ['a', 'B'].sort(naturalSort({ caseSensitive: true }))
⏵ ['B', 'a']
⏴ ['a10', 'a', 'a2'].sort(naturalSort())
⏵ ['a', 'a2', 'a10']
⏴ ['1.16.0', '1.2.0', '1.16.0-beta'].sort(naturalSort())
⏵ [ '1.16.0-beta', '1.16.0', '1.2.0' ]
Based on The Aplhanum Algorithm by Dave Koelle.
Original version published in Javascript Natural Sort Algorithm With Unicode Support by Jim Palmer.