Skip to content

Instantly share code, notes, and snippets.

@mindon
Last active March 13, 2024 06:46
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 mindon/c6682ed68e0a92e242e88482d362c1bb to your computer and use it in GitHub Desktop.
Save mindon/c6682ed68e0a92e242e88482d362c1bb to your computer and use it in GitHub Desktop.
sort a object array with string attributes
const arr = [{attr:'x', value: 2}, {attr:'y', value: 2}, {attr:'z', value: 1}];
// descend
arr.sort((a,b,x='attr')=>+(a[x]<b[x])-+(a[x]>b[x]));
console.log(arr.slice(0));
// ascend
arr.sort((a,b,x='attr')=>+(a[x]>b[x])-+(a[x]<b[x]));
console.log(arr.slice(0));
// multiple attributes descend
arr.sort((a,b,l=['value','attr'])=>l.reduce((r,x)=>r||(+(a[x]<b[x])-+(a[x]>b[x])),0));
console.log(arr.slice(0));
// multiple attributes ascend with order customized
arr.sort((a,b,l=['value','attr'],dir={'attr':-1})=>l.reduce((r,x)=>r||(dir[x]||1)*(+(a[x]>b[x])-+(a[x]<b[x])),0));
console.log(arr.slice(0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment