Created
September 18, 2019 19:07
-
-
Save mikemcbride/c73fc625e9deb702a223e59539229dbb to your computer and use it in GitHub Desktop.
Lightweight function that mostly replaces lodash's sortBy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// takes an array of objects, an array of properties to sort by, | |
// and optionally a case-sensitive parameter (defaults to false) | |
// returns an array sorted by the given properties, in order. | |
const sortBy = function(arr, props, sensitive = false) { | |
// make sure we have an array. | |
if (!Array.isArray(props)) { | |
props = [props] | |
} | |
return arr.sort((a, b) => { | |
return props | |
.map(prop => { | |
let dir = 1 | |
if (prop[0] === '-') { | |
// they want a reverse sort | |
dir = -1 | |
prop = prop.substring(1) | |
} | |
// sort should be case insensitive | |
const _a = | |
typeof a[prop] === 'string' && sensitive === false | |
? a[prop].toLowerCase() | |
: a[prop] | |
const _b = | |
typeof b[prop] === 'string' && sensitive === false | |
? b[prop].toLowerCase() | |
: b[prop] | |
return _a > _b ? dir : _a < _b ? -dir : 0 | |
}) | |
.reduce((p, n) => { | |
return p ? p : n | |
}, 0) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment