Tuesday, June 28, 2011
Javascript Array Sort Custom Comparator
Javascript Array.sort() allows you to define custom comparators!
var numbers = [10, 20, 5, -10, 30];
// Sorting in ascending order.
// Sorting in descending order
var numbers = [10, 20, 5, -10, 30];
// Sorting in ascending order.
numbers.sort(function(a, b){return a-b;});
// Sorting in descending order
numbers.sort(function(a, b){return b-a;});