Skip to content

Instantly share code, notes, and snippets.

@mindon
Last active May 23, 2024 02:53
Show Gist options
  • 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