sort-by-key
v1.0.1
Published
Provides a means to sort an array or object be a value of a given key.
Downloads
83
Maintainers
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