Blog

In JavaScript Sort Numbers using the sort() Function
Posted on November 28, 2017 in Algorithms, JavaScript by Matt Jennings

Sort Numbers In Ascending Order

var numbers = [2, 1, 111, 222, 33, -2];

// Output is [-19, -2, 1, 33, 111, 222]
// because the 'return a - b' code below
// means that in the array above
// 2 (index 0) is subtracted 1 (index 1)
// and since this number is positive
// 2 is moved in front of 1 and so on
console.log(numbers.sort(function(a,b) {
  return a - b;
}));

Sort Numbers in Descending Order

var numbers = [2, 1, 111, 222, 33, -2];

// Output is [222, 111, 33, 2, 1, -2]
// because the 'return b - a' code below
// means that in the array above
// 1 (index 1) is subtracted 2 (index 0)
// and since this number is negative
// 2 stays in front of 1 and so on
console.log(numbers.sort(function(a,b) {
  return b - a;
}));

Leave a Reply