Package Exports
- sort-by-key
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (sort-by-key) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Sort By Key
This utility provides a simple means to sort elements of an array or an object by a given key.
Installation
$ npm install sort-by-key
Usage
There are two ways of executing the sorting, one is by using the function;
const SortByKey = require('sort-by-key');
const data = [{
value: 'hello',
weight: 10
}, {
value: 'world',
weight: -10
}, {
value: 'foo'
}];
SortByKey(data, 'weight');
This will sort the array like;
[{
value: 'world',
weight: -10
}, {
value: 'foo'
}, {
value: 'hello',
weight: 10
}]
This can also be reveresed like;
SortByKey(data, 'weight', true);
and would return;
[{
value: 'hello',
weight: 10
}, {
value: 'foo'
}, {
value: 'world',
weight: -10
}]
You can also use function's to return the key weight value, for example;
[{
value: 'hello',
weight: function () { return 10; }
}, {
value: 'world',
weight: -10
}, {
value: 'foo'
}]
You can also sort object's like;
const data = {
world: 'world',
hello: { weight: -1 },
foo: 'bar',
bar: { weight: 1 }
}
SortByKey(data, 'weight');
and this will return;
{
hello: { weight: -1 },
world: 'world',
foo: 'bar',
bar: { weight: 1 }
}
Array and Object
There is an attach function which will attach the sortByKey functions to the Array and Object classes. And this is done by calling;
require('sort-by-key').attach();
Then the sortByKey functions can be access like;
// Array.
Array.sortByKey(data, 'weight');
data.sortByKey('weight');
// Object.
Object.sortByKey(data, 'weight');
data.sortByKey('weight');
Testing
A mocha test suite has been provided and can be run by:
$ npm test