JavaScript sort

Learn how to perform a JavaScript sort with alphabetical and numeric data.

Text sort

Alphabetical – Ascending

var colors = ["green", "red", "purple", "blue"];
colors.sort(); //blue, green, purple, red

Alphabetical – Descending

var colors = ["green", "red", "purple", "blue"];
colors.sort();
colors.reverse(); //red, purple, green, blue

Number sort

var numbers = [4,15,7,100];
numbers.sort(); //100, 15, 4, 7

The sort function doesn’t work as well with numbers as it does with text. You will have to tweak the sort function so that it will work correctly.

Numerical – Ascending

var numbers = [4,15,7,100];
numbers.sort(function(a,b){return a > b ? 1 : -1}) 
//4, 7, 15, 100

Numerical – Descending

var numbers = [4,15,7,100];
numbers.sort(function(a,b){return a > b ? -1 : 1}) 
//100, 15, 7, 4