javascript sort function sorting wrong [duplicate]

跟風遠走 提交于 2020-06-22 10:08:48

问题


Hello I have a textbox having values like

<input type="hidden" value="2,1,4,5,3,6,7,8,9,10,11,12" class="sortvalues" id="1_1_parent">

Now what I want to take the value of this textbox, want to split the values to array and then as last result I need a sorted array.

What I have done.

 allsortedValues =  $(".sortvalues").val();
 allsortedValues = allsortedValues.split(",");
 allsortedValues = allsortedValues.sort();

When I check the array

 console.log(allsortedValues);

It shows

  1,10,11,12,2,3,4,5,6,7,8,9

Sorting array as 1, 10, 11, 12, 2.....

I have even used

allsortedValues = allsortedValues.split(",").map(function(x){return parseInt(x)});

before applying sort and in other case I have even used parseInt like

for(var i = 0; i < allsortedValues.length; i++) {

   allsortedValues[i] = parseInt(allsortedValues[i]);
}

before applying sort but in all cases result is same. Will some one guide what am I doing wrong?


回答1:


You'll have to pass in a comparator function that converts the strings to numbers:

allsortedvalues = allsortedvalues.sort(function(a,b) {
  return (+a) - (+b);
});

If there's a chance that some of your array entries aren't nicely-formatted numbers, then your comparator would have to get more complicated.

The construction (+a) involves the unary + operator, which doesn't do anything if a is already a number. However if a is not a number, the result of +a will be either the value of a when interpreted as a number, or else NaN. A string is interpreted as a number in the obvious way, by being examined and parsed as a string representation of a number. A boolean value would be converted as false -> 0 and true -> 1. The value null becomes 0, and undefined is NaN. Finally, an object reference is interpreted as a number via a call to its valueOf() function, or else NaN if that doesn't help.

It's equivalent to use the Number constructor, as in Number(a), if you like. It does exactly the same thing as +a. I'm a lazy typist.




回答2:


If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

To compare numbers instead of strings, the compare function can simply subtract b from a:

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

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort



来源:https://stackoverflow.com/questions/15765236/javascript-sort-function-sorting-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!