Skip to content

Instantly share code, notes, and snippets.

@mikemcbride
Created September 18, 2019 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikemcbride/c73fc625e9deb702a223e59539229dbb to your computer and use it in GitHub Desktop.
Save mikemcbride/c73fc625e9deb702a223e59539229dbb to your computer and use it in GitHub Desktop.
Lightweight function that mostly replaces lodash's sortBy
// 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