Created
August 17, 2018 22:07
-
-
Save HenrikJoreteg/4aabbe35b9f1fb878978f2c7c85ccab9 to your computer and use it in GitHub Desktop.
get an array sort function
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
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 | |
} |
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
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