npm

Need private packages and team management tools?Check out npm Orgs. »

sort-by-chain

0.0.9 • Public • Published

sort-by-chain

build state install size MIT License

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

install

npm i sort-by-chain

Downloadsweekly downloads

8

version

0.0.9

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability