Provides array functions
npm install @romatech/order-byArray.prototype with:
orderBy / orderByDesc
thenBy / thenByDesc
distinct / distinctBy
Array.prototype.
bash
npm install @romatech/order-by
`
๐ฆ Usage
> โ
You must import the package once to enable prototype extensions.
$3
`js
require('@romatech/order-by');
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 30 },
];
const sorted = users
.orderBy(u => u.age)
.thenBy(u => u.name);
console.log(sorted);
`
$3
`js
import '@romatech/order-by';
const products = [
{ price: 100, rating: 4.5 },
{ price: 100, rating: 4.8 },
{ price: 90, rating: 4.2 },
];
const sorted = products
.orderByDesc(p => p.price)
.thenBy(p => p.rating);
console.log(sorted);
`
๐ง API
$3
array.orderBy(fn)
Sort ascending by selector
array.orderByDesc(fn)
Sort descending by selector
array.thenBy(fn)
Chain secondary ascending sort
array.thenByDesc(fn)
Chain secondary descending sort
`js
const arr = [
{ name: 'A', age: 25 },
{ name: 'B', age: 30 },
{ name: 'C', age: 30 },
];
const sorted = arr
.orderBy(x => x.age)
.thenBy(x => x.name);
`
$3
array.distinct()
Removes deep-equal duplicates (via JSON.stringify)
array.distinctBy(fn)
Removes duplicates based on selector return value
`js
const arr = [
{ id: 1, name: 'A' },
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
];
arr.distinct();
// โ [{ id: 1, name: 'A' }, { id: 2, name: 'B' }]
arr.distinctBy(x => x.id);
// โ [{ id: 1, name: 'A' }, { id: 2, name: 'B' }]
`
๐งฑ TypeScript Support
Includes full typings via index.d.ts.
`ts
type Selector = (item: T) => any;
interface OrderedArray extends Array {
thenBy(fn: Selector): OrderedArray;
thenByDesc(fn: Selector): OrderedArray;
}
interface Array {
orderBy(fn: Selector): OrderedArray;
orderByDesc(fn: Selector): OrderedArray;
distinct(): T[];
distinctBy(fn: Selector): T[];
}
`
โ
Compatibility
- Node.js LTS (โฅ v18)
- Works in browsers (via bundlers like Vite/Webpack)
- Fully compatible with CommonJS and ESM
๐งช Tests
`bash
npm install
npm test
`
All tests are implemented with Jest and validate sorting logic and method chaining behavior.
โ ๏ธ Prototype Extension Warning
This package extends Array.prototype with non-enumerable methods:
- orderBy, orderByDesc
- thenBy, thenByDesc
- distinct, distinctBy`