Skip to content

Instantly share code, notes, and snippets.

@founddrama
Created February 11, 2011 15:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save founddrama/822463 to your computer and use it in GitHub Desktop.
Save founddrama/822463 to your computer and use it in GitHub Desktop.
Enough with the `if (a > b) { } else if (a < b) { } else { }` stuff, OK? If you've got numbers, you can sort with a one-liner as follows...
var arr = [10, 5, 6, 1, -2, 28];
function ascending(a, b){
return ( (a - b) / Math.abs(a - b) ) || 0;
}
function descending(a, b){
return ( (b - a) / Math.abs(b - a) ) || 0;
}
arr.sort(ascending);
// [-2,1,5,6,10,28]
arr.sort(descending);
// [28,10,6,5,1,-2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment