How to sort an array of integers correctly

  1. Home
  2. javascript
  3. How to sort an array of integers correctly

Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought.

var numArray = [140000, 104, 99];
numArray = numArray.sort();
alert(numArray)

I’d expect this to show 99, 104, 140000. Instead it shows 104, 140000, 99. So it seems the sort is handling the values as strings.

Is there a way to get the sort function to actually sort on integer value?

First answer

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

function sortNumber(a, b) {
  return a - b;
}

var numArray = [140000, 104, 99];
numArray.sort(sortNumber);

console.log(numArray);

In ES6, you can simplify this with arrow functions:

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort

Second answer

array.sort does a lexicographic sort by default, for a numeric sort, provide your own function. Here’s a simple example:

function compareNumbers(a, b)
{
    return a - b;
}

numArray.sort(compareNumbers);

Also note that sort works “in place”, there’s no need for the assignment.

Third answer

This answer is equivalent to some of the existing answers, but ECMAScript 6 arrow functions provide a much more compact syntax that allows us to define an inline sort function without sacrificing readability:

numArray = numArray.sort((a, b) => a - b);

It is supported in most browsers today.

Reprint:https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly
Spread the love

Related articles

Comments are closed.