Last active
November 21, 2024 05:06
-
-
Save mindon/c6682ed68e0a92e242e88482d362c1bb to your computer and use it in GitHub Desktop.
sort a object array with string attributes: descend +<->, ascend -<+>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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