Sorting in JavaScript array. How can I sort this array properly? [duplicate]

Solution 1:

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) {
  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).

Also examples of sorting objects by key.

Solution 2:

Just building on all of the above answers, they can also be done in one line like this:

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

//outputs: 99, 104, 140000

Solution 3:

I am surprised why everyone recommends to pass a comparator function to sort(), that makes sorting really slow!

To sort numbers, just create any TypedArray:

var numArray = new Float64Array([140000, 104, 99]);
numArray = numArray.sort();
console.log(numArray)