Home How to sort an array of integers correctly
Reply: 10

How to sort an array of integers correctly

peirix
1#
peirix Published in 2009-06-30 10:43:11Z

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[0] + ", " + numArray[numArray.length - 1]);

I'd expect this to show "99, 140000". Instead it shows "104, 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?

fareed namrouti
2#
fareed namrouti Reply to 2015-08-29 00:49:46Z

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);
alert(numArray.join(","));
Paul Dixon
3#
Paul Dixon Reply to 2009-06-30 10:47:55Z

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.

Peter Mortensen
4#
Peter Mortensen Reply to 2017-09-25 19:08:31Z

In JavaScript the sort() method's default behaviour is to sort values in an array alphabetically.

To sort by number you have to define a numeric sort function (which is very easy):

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

numArray = numArray.sort(sortNumber);
MiniGod
5#
MiniGod Reply to 2016-10-07 11:45:19Z

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

var numArray = [140000, 104, 99];

// ES5
numArray = numArray.sort(function (a, b) {  return a - b;  });

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

//outputs: 99, 104, 140000
Peter Mortensen
6#
Peter Mortensen Reply to 2017-09-25 19:09:14Z

Here is my sort array function in the utils library:

sortArray: function(array) {
    array.sort(function(a, b) {
        return a > b;
    });
},

# Let's test a string array
var arr = ['bbc', 'chrome', 'aux', 'ext', 'dog'];
utils.sortArray(arr);
console.log(arr);
>>> ["aux", "bbc", "chrome", "dog", "ext", remove: function]

# Let's test a number array
var arr = [55, 22, 1425, 12, 78];
utils.sortArray(arr);
console.log(arr);
>>> [12, 22, 55, 78, 1425, remove: function]
SpYk3HH
7#
SpYk3HH Reply to 2014-11-18 19:41:00Z

I agree with aks, however instead of using

return a - b;

You should use

return a > b ? 1 : a < b ? -1 : 0;
Peter Mortensen
8#
Peter Mortensen Reply to 2017-09-25 19:10:34Z

Try this code:

HTML:

<div id="demo"></div>

JavaScript code:

<script>
    (function(){
        var points = [40, 100, 1, 5, 25, 10];
        document.getElementById("demo").innerHTML = points;
        points.sort(function(a, b){return a-b});
        document.getElementById("demo").innerHTML = points;
    })();
</script>
Peter Mortensen
9#
Peter Mortensen Reply to 2017-09-25 19:11:41Z

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.

Peter Mortensen
10#
Peter Mortensen Reply to 2017-09-25 19:12:47Z

Array.prototype.sort() is the go to method for sorting arrays, but there are a couple of issues we need to be aware of.

The sorting order is by default lexicographic and not numeric regardless of the types of values in the array. Even if the array is all numbers, all values will be converted to string and sorted lexicographically.

So should we need to customize the sort() and reverse() method like below.

Referred URL

For sorting numbers inside the array

numArray.sort(function(a, b)
{
    return a - b;
});

For reversing numbers inside the array

numArray.sort(function(a, b)
{
    return b - a;
});

Referred URL

Commercial Suicide
11#
Commercial Suicide Reply to 2016-06-26 18:34:50Z

The question has already been answered, the shortest way is to use sort() method. But if you're searching for more ways to sort your array of numbers, and you also love cycles, check the following

Insertion sort

Ascending:

var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length; i++) {
    var target = numArray[i];
    for (var j = i - 1; j >= 0 && (numArray[j] > target); j--) {
        numArray[j+1] = numArray[j];
    }
    numArray[j+1] = target
}
console.log(numArray);

Descending:

    var numArray = [140000, 104, 99];
    for (var i = 0; i < numArray.length; i++) {
        var target = numArray[i];
        for (var j = i - 1; j >= 0 && (numArray[j] < target); j--) {
            numArray[j+1] = numArray[j];
        }
        numArray[j+1] = target
    }
    console.log(numArray);

Selection sort:

Ascending:

var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
    var min = i;
    for (var j = i + 1; j < numArray.length; j++) {
        if (numArray[j] < numArray[min]) {
            min = j;
        }
    }
    if(min != i) {
        var target = numArray[i];
        numArray[i] = numArray[min];
        numArray[min] = target;
    }
}
console.log(numArray);

Descending:

var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
    var min = i;
    for (var j = i + 1; j < numArray.length; j++) {
        if (numArray[j] > numArray[min]) {
            min = j;
        }
    }
    if(min != i) {
        var target = numArray[i];
        numArray[i] = numArray[min];
        numArray[min] = target;
    }
}
console.log(numArray);

Have fun

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.354596 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO