lihai 8d6c751f49 feat: push | 2 years ago | |
---|---|---|
.. | ||
node_modules | 2 years ago | |
LICENSE | 2 years ago | |
README.md | 2 years ago | |
index.js | 2 years ago | |
package.json | 2 years ago |
Get a compare function for array to sort
$ npm install --save compare-func
var compareFunc = require('compare-func');
// sort by an object property
[{x: 'b'}, {x: 'a'}, {x: 'c'}].sort(compareFunc('x'));
//=> [{x: 'a'}, {x: 'b'}, {x: 'c'}]
// sort by a nested object property
[{x: {y: 'b'}}, {x: {y: 'a'}}].sort(compareFunc('x.y'));
//=> [{x: {y: 'a'}}, {x: {y: 'b'}}]
// sort by the `x` propery, then `y`
[{x: 'c', y: 'c'}, {x: 'b', y: 'a'}, {x: 'b', y: 'b'}].sort(compareFunc(['x', 'y']));
//=> [{x: 'b', y: 'a'}, {x: 'b', y: 'b'}, {x: 'c', y: 'c'}]
// sort by the returned value
[{x: 'b'}, {x: 'a'}, {x: 'c'}].sort(compareFunc(function(el) {
return el.x;
}));
//=> [{x: 'a'}, {x: 'b'}, {x: 'c'}]
Returns a compare function for array to sort
Type: string
, function
or array
of either
If missing it sorts on itself.
The string can be a dot path to a nested object property.
MIT © Steve Mao