Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created November 14, 2021 04:32
Show Gist options
  • Select an option

  • Save DavidWells/bb5dab17f668548962e9953c2b8d83eb to your computer and use it in GitHub Desktop.

Select an option

Save DavidWells/bb5dab17f668548962e9953c2b8d83eb 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