Skip to content

Instantly share code, notes, and snippets.

@bschlenk
Created June 1, 2019 19:20
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 bschlenk/262e5f6e835d4defc66547c770647f37 to your computer and use it in GitHub Desktop.
Save bschlenk/262e5f6e835d4defc66547c770647f37 to your computer and use it in GitHub Desktop.
A function to easily sort JS objects by key.
/**
* Create a sorting function that can sort objects by a calculated key. Can be passed to `Array.sort`.
* @param cb A function that will be passed each object and expected to return a key to sort by.
* The key can be either a string, number, or an array of those.
* @return A function that can be passed to `Array.sort`.
*/
function sortBy(cb) {
const stringCompare = (a, b) => a.localeCompare(b);
const numberCompare = (a, b) => a - b;
const arrayCompare = (a, b) => {
let result = 0;
for (let i = 0; i < a.length; ++i) {
const aVal = a[i];
const bVal = b[i];
result = compare(aVal, bVal);
if (result !== 0) {
return result;
}
}
return result;
}
const compare = (a, b) => {
if (typeof a === 'string') {
return stringCompare(a, b);
}
if (typeof a === 'number') {
return numberCompare(a, b);
}
if (Array.isArray(a)) {
return arrayCompare(a, b);
}
throw new Error('Cannot compare objects of type ' + typeof a);
}
const getKey = typeof cb === 'string'
? a => a[cb]
: cb;
return (a, b) => compare(getKey(a), getKey(b));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment