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 00:51

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
查看更多
美炸的是我
3楼-- · 2018-12-31 00:56

Try this code as below

var a = [5, 17, 29, 48, 64, 21];
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
})
;} 
alert(sortA(a));
查看更多
深知你不懂我心
4楼-- · 2018-12-31 00:56

to handle undefined, null, and NaN: Null behaves like 0, NaN and undefined goes to end.

array = [3, 5, -1, 1, NaN, 6, undefined, 2, null]
array.sort((a,b) => isNaN(a) || a-b)
// [-1, null, 1, 2, 3, 5, 6, NaN, undefined]
查看更多
浅入江南
5楼-- · 2018-12-31 00:58

I agree with aks, however instead of using

return a - b;

You should use

return a > b ? 1 : a < b ? -1 : 0;
查看更多
何处买醉
6楼-- · 2018-12-31 00:59

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.

查看更多
十年一品温如言
7楼-- · 2018-12-31 01:01

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.

查看更多
登录 后发表回答