Skip to content

Instantly share code, notes, and snippets.

@victornpb
Last active January 18, 2021 01:16
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 victornpb/03171ef83ad9dfc5342722c61e11f6a0 to your computer and use it in GitHub Desktop.
Save victornpb/03171ef83ad9dfc5342722c61e11f6a0 to your computer and use it in GitHub Desktop.
Sort by field
function sortBy(arr, fields) {
if (typeof fields === 'string') fields = [fields];
function compareFn(a, b) {
return fields
.map(field => {
let dir = 1;
if (field[0] === "-") {
dir = -1;
field = field.substring(1);
}
return a[field] > b[field] ? dir : a[field] < b[field] ? -dir : 0;
})
.reduce((p, n) => (p ? p : n), 0);
}
return arr.slice().sort(compareFn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment