@philiprehberger/natural-sort
v0.2.0
Published
Natural string sorting — file2 before file10, not after
Readme
@philiprehberger/natural-sort
Natural string sorting -- file2 before file10, not after.
Installation
npm install @philiprehberger/natural-sortUsage
import { naturalSort, naturalCompare } from '@philiprehberger/natural-sort';
// Sort file names naturally
naturalSort(['file10', 'file2', 'file1', 'file20']);
// => ['file1', 'file2', 'file10', 'file20']
// Case insensitive
naturalSort(['Banana', 'apple', 'Cherry'], { caseInsensitive: true });
// => ['apple', 'Banana', 'Cherry']
// Descending
naturalSort(['v1', 'v10', 'v2'], { descending: true });
// => ['v10', 'v2', 'v1']
// Sort objects with accessor
const items = [{ name: 'item10' }, { name: 'item2' }, { name: 'item1' }];
naturalSort(items, { accessor: (i) => i.name });
// => [{ name: 'item1' }, { name: 'item2' }, { name: 'item10' }]
// Low-level comparison
naturalCompare('file2', 'file10'); // negative (file2 < file10)
// Negative numbers sort numerically too
naturalCompare('-10', '-2'); // negative (-10 < -2)Sort by Key
import { naturalSortBy } from '@philiprehberger/natural-sort';
const items = [{ name: 'item10' }, { name: 'item2' }, { name: 'item1' }];
naturalSortBy(items, 'name');
// => [{ name: 'item1' }, { name: 'item2' }, { name: 'item10' }]API
naturalSort<T>(array: T[], options?: NaturalSortOptions<T>): T[]
Returns a new sorted array without mutating the original.
Options:
| Option | Type | Default | Description |
| ----------------- | ------------------ | ------- | ------------------------------ |
| caseInsensitive | boolean | false | Ignore case when comparing |
| descending | boolean | false | Sort in descending order |
| accessor | (item: T) => string | - | Extract string from each item |
naturalSortBy<T>(array: T[], key: keyof T, options?: NaturalSortOptions<T>): T[]
Type-safe shorthand that infers string-typed keys of T and sorts by that key.
naturalCompare(a: string, b: string, caseInsensitive?: boolean): number
Compares two strings using natural ordering. Returns negative, zero, or positive. Recognizes leading negative integers when not following an alphanumeric character.
Development
npm install
npm run build
npm testSupport
If you find this project useful:
