# 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();

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?

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
``````

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.

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
Save 55.0% on select products from Lekebaby with promo code 55KDBMFC, through 11/1 while supplies last. 