Skip to content

Instantly share code, notes, and snippets.

@HenrikJoreteg
Created August 17, 2018 22:07
Show Gist options
  • Save HenrikJoreteg/4aabbe35b9f1fb878978f2c7c85ccab9 to your computer and use it in GitHub Desktop.
Save HenrikJoreteg/4aabbe35b9f1fb878978f2c7c85ccab9 to your computer and use it in GitHub Desktop.
get an array sort function
export default (property, ascOrDesc = 'asc') => (a, b) => {
const asc = ascOrDesc === 'asc'
const valA = a[property]
const valB = b[property]
if (valA > valB) {
return asc ? 1 : -1
}
if (valB > valA) {
return asc ? -1 : 1
}
return 0
}
import getSortByFn from './get-array-sorter'
const people = [{name: 'Henrik'}, {name: 'Arunesh'}, {name: 'Bryan'}, {name: 'Tim'}]
// note that array.sort sorts items in place, if you want a copy of the array do this
const copy = people.slice()
copy.sort(getSortByFn('name', 'desc'))
// or
copy.sort(getSortByFn('name', 'asc'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment