How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) –

var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
  if( a === Infinity ) 
    return 1; 
  else if( isNaN(a)) 
    return -1;
  else 
    return a - b;
});

console.log(numArray);

Documentation:

Mozilla Array.prototype.sort() recommends this compare function for arrays that don’t contain Infinity or NaN. (Because Infinity - Infinity is NaN, not 0). This was solved by Sergio Abreu’s edition, handling NaN and Infinity inside the function.

Also examples of sorting objects by key.

Leave a Comment

tech