natsort2
v1.0.1
Published
Natural string sorting
Maintainers
Readme
natsort2-js: Natural String Sorting in JavaScript
No regexp. No copy. No parsing number. No dependency.
Sorting rules:
- Numeric substrings are compared based on their integer values.
a1 < a2 < a10 < a11 < a20. - Leading zeros in numeric substrings are ignored during comparison.
a001 < a2 < a010 < a11 < a00020. - If the integer values are equal, more leading zeros means a smaller value.
a001 < a01 < a1 - Digits come before non-digits.
a1 < a_,a1 < aa. - Non-numeric substrings are compared by unicode code point.
aa < ab,aa < a中. - The shorter string is considered smaller.
a < aa.
Notices:
9.9 < 9.11a01b2 < a1b1- Two strings are considered equal only if they are exactly the same.
- Strings are compared in unicode char by char (not byte).
Usage
npm install natsort2ESM / CommonJS
import compare from 'natsort2';
// or
import { compare } from 'natsort2';
// or
const { compare } = require('natsort2');
const strArray = ['a', 'a1', 'a11', 'a2', 'a20', 'a001', 'a01', 'aa', 'ab'];
console.log(strArray);
console.log(strArray.toSorted(compare));
console.log(strArray);
strArray.sort(compare);
console.log(strArray);Browser UMD / ESM
<script src="./dist/natsort2.umd.min.js"></script>
<script>
const { compare } = NatSort2;
</script>
<script type="module">
const { compare } = await import('./dist/natsort2.min.mjs');
</script>Similar Projects
- https://github.com/litejs/natural-compare-lite
- https://github.com/ganlvtech/go-natsort
- https://github.com/facette/natsort
- https://github.com/maruel/natural
- https://github.com/skarademir/naturalsort
