How to sort an array of integers correctly

2018-12-31 00:40发布

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?

17条回答
墨雨无痕
2楼-- · 2018-12-31 01:12

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>
查看更多
笑指拈花
3楼-- · 2018-12-31 01:14

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);
查看更多
刘海飞了
4楼-- · 2018-12-31 01:14

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

To sort numbers, just create any TypedArray:

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

查看更多
笑指拈花
5楼-- · 2018-12-31 01:14

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]
查看更多
刘海飞了
6楼-- · 2018-12-31 01:15

For a normal array of elements values only:

function sortArrayOfElements(arrayToSort) {
    function compareElements(a, b) {
        if (a < b)
            return -1;
        if (a > b)
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareElements);
}

e.g. 1:
var array1 = [1,2,545,676,64,2,24]
**output : [1, 2, 2, 24, 64, 545, 676]**

var array2 = ["v","a",545,676,64,2,"24"]
**output: ["a", "v", 2, "24", 64, 545, 676]**

For an array of objects:

function sortArrayOfObjects(arrayToSort, key) {
    function compareObjects(a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareObjects);
}

e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]

**output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]**
查看更多
登录 后发表回答