Skip to content

Instantly share code, notes, and snippets.

@danwarfel
Created December 8, 2015 15:27
Show Gist options
  • Save danwarfel/566b9e1877ee31fce8ee to your computer and use it in GitHub Desktop.
Save danwarfel/566b9e1877ee31fce8ee to your computer and use it in GitHub Desktop.

Sorting in JavaScript

Like a boss.

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b}); //Sort numbers (numerically and ascending)
points.sort(function(a, b){return b-a}); //Sort numbers (numerically and descending)
var brands = ["Sony", "HTC", "Apple", "i-mobile", "Motorola"];
brands.sort(); //Alphabetically, ascending and case-sensitive
brands.reverse(); //Alphabetically, descending and case-sensitive
var stringArr = ['A', 'C', 'B', 'a', 'c', 'b', 'A'];
stringArr.sort(function(a, b) { //Alphabetically, ascending and case-insensitive
a = a.toLowerCase();
b = b.toLowerCase();
if (a > b) return 1;
else if (a < b) return -1;
else return 0;
});
stringArr.sort(function(a, b) { //Alphabetically, descending and case-insensitive
a = a.toLowerCase();
b = b.toLowerCase();
if (a > b) return -1;
else if (a < b) return 1;
else return 0;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment