Archive

javascript sorting of integer arrays

This is famous gotcha in JavaScript: How to sort an array of two digit integers. JavaScript will treat the values in the array as strings when sorting, so there is a special trick that needs to be performed: call back function as a .sort() parameter.

function numberSorter(a, b) {
  return a - b;
}
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
numbers.sort(numberSorter);

Comments: