compare-by
v2.1.1
Published
A versatile utility library for sorting arrays of objects by one or multiple keys with customizable sort directions.
Maintainers
Readme
compare-by
Type-safe comparators for sorting arrays by one or more object properties, including nested values selected by a callback.
Installation
pnpm add compare-by
# or
npm install compare-byUsage
import { compareBy } from 'compare-by';
const people = [
{ name: { first: 'Ada', last: 'Lovelace' }, age: 36, active: true },
{ name: { first: 'Grace', last: 'Hopper' }, age: 85, active: false },
];
// One property; `asc` is the default direction.
people.sort(compareBy({ key: 'age' }));
// A callback can select a nested property.
people.sort(compareBy({ key: (person) => person.name.last, dir: 'desc' }));
// Compare properties in order until one differs.
people.sort(compareBy([
{ key: 'active', dir: 'desc' },
{ key: (person) => person.name.last },
]));API
compareBy(props)
Returns an Array.prototype.sort comparator. props accepts one CompareKey or an array of them. Keys are evaluated in order, so later keys break ties from earlier keys.
type CompareDirection = 'asc' | 'desc';
type CompareKey<T> = {
key: keyof T | ((value: T) => unknown);
dir?: CompareDirection;
};
function compareBy<T>(props: CompareKey<T> | CompareKey<T>[]): (a: T, b: T) => number;The selected values must be strings, numbers, booleans, or Date instances. Other values cause compareBy to throw an Unsupported data type for comparison error when sorting.
Value comparators
The package also exports compareStrings, compareNumbers, compareBooleans, compareDates, and compareValues for direct use. All accept (a, b, dir?) and return a negative number, zero, or a positive number.
- Strings use
localeCompare. - Dates compare their timestamps.
- Booleans sort
truebeforefalsein ascending order. compareValuesdispatches to the matching comparator and throws for unsupported or mixed value types.
Development
This repository uses pnpm 11.
pnpm install --frozen-lockfile
pnpm lint
pnpm test
pnpm buildout/ is generated during the build and before npm publication; do not commit it. Add a changeset with pnpm changeset for every user-facing change. The release workflow creates a version PR and publishes it after that PR is merged.
Contributing
Please use the bug report or feature request template. Include a focused test with behavior changes.
