sort-by-chain
v0.0.9
Published
Provides a way to sorting by key or multiple keys with specific order type
Downloads
28
Maintainers
Readme
sort-by-chain
Sort array by one or chain of properties with custom comparators
Experimental project. There is possibility of critical bugs and breaking changes in future.
Install
$ npm install --save sort-by-chain
or
$ yarn add sort-by-chain
Usage
Simple sorting
Import package:
import { sortBy } from 'sort-by-chain';
With sortBy
you just write keys as strings. Custom comparators are not supported this way.
sortBy(animals, '-age', 'pet');
/*
[
{ pet: 'dog', age: 5, name: 'Furball' },
{ pet: 'alpaca', age: 4 },
{ pet: 'cat', age: 4 },
{ pet: 'dog', age: 3, name: 'Ruffles' },
]
*/
More customized sorting
Import package:
import { sortByChain } from 'sort-by-chain';
With sortByChain
you can specify sorting chain with some customizations.
const animals = [
{ pet: 'dog', age: 5, name: 'Furball' },
{ pet: 'cat', age: 4 },
{ pet: 'ox', age: 4 },
{ pet: 'dog', age: 3, name: 'Ruffles' },
{ pet: 'alpaca', age: 4 },
];
const chain = [
{ valueGetter: it => it.age, reverse: true },
{ valueGetter: it => it.pet },
];
sortByChain(animals, chain);
/*
[
{ pet: 'dog', age: 5, name: 'Furball' },
{ pet: 'alpaca', age: 4 },
{ pet: 'cat', age: 4 },
{ pet: 'ox', age: 4 },
{ pet: 'dog', age: 3, name: 'Ruffles' },
];
*/
You can also specify custom comparators.
const stringLengthComparator = (a, b) => b.length - a.length;
const chain = [{ valueGetter: it => it.pet, comparator: stringLengthComparator }];
sortByChain(animals, chain)
/*
[
{ pet: 'ox', age: 4 },
{ pet: 'dog', age: 5, name: 'Furball' },
{ pet: 'cat', age: 4 },
{ pet: 'dog', age: 3, name: 'Ruffles' },
{ pet: 'alpaca', age: 4 },
];
*/
License
MIT