Skip to content

Instantly share code, notes, and snippets.

@Uvacoder
Forked from DavidWells/sort-on-object-key.js
Created January 1, 2022 22:31
Show Gist options
  • Select an option

  • Save Uvacoder/2262d1f84ba68ddb68b54d5164f51369 to your computer and use it in GitHub Desktop.

Select an option

Save Uvacoder/2262d1f84ba68ddb68b54d5164f51369 to your computer and use it in GitHub Desktop.
Sort an array by key of object in array
// https://github.com/softvar/js/blob/master/packages/util-array/src/index.ts#L97
function sortOnKey(arr, key, direction = 'asc' ) {
if (!arr || !arr.length || !key) {
return [];
}
const dir = direction === 'asc' ? 1 : -1
arr.sort((a, b) => {
return b[key] > a[key] ? -1 : a[key] > b[key] ? dir : 0;
});
return arr;
}
var x = [{
name: 'zod',
age: 11,
}, {
name: 'bob',
age: 32
}]
sortOnKey(x, 'age', 'desc')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment