9

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?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
  • 4
    http://stackoverflow.com/questions/1063007/sort-not-working-with-integers It is possible duplicated – Dzung Nguyen Apr 02 '13 at 13:23
  • Your sort is working fine, javascript is treating your input as strings instead of numbers hence the unexpected behavior. See @Pointy's answer for a proper solution. – Kyle Apr 02 '13 at 13:26

2 Answers2

24

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    I guess the `(+a)` stuff might not be strictly necessary, but I find it nice to highlight what's going on a little. – Pointy Apr 02 '13 at 13:24
  • 3
    `(+)`'ses look quite confusing. I'd suggest `Number(a)-Number(b)` if you want to be explicit. – georg Apr 02 '13 at 13:25
  • @thg435 agree, I prefer human language :) – Dzung Nguyen Apr 02 '13 at 13:27
  • Personally I think just `return a - b;//compare two numbers` with a comment is clear enough. – Kyle Apr 02 '13 at 13:27
  • `(+a)` is just using coersion, something you should understand if you're writing JavaScript. This comment thread has me wondering, though, is `(+a)` congruent to `Number(a)`? That is, does the interpreter do the same thing in either case? – James Sumners Apr 02 '13 at 13:55
  • @JamesSumners sorry to be almost 5 years late, but yes `+a` will do precisely the same thing as `Number(a)`. – Pointy Dec 06 '17 at 13:59
  • 1
    @Pointy just want to comment, for a lazy typist, you sure are not lazy to type all those epxlanation about +a being equivalent to Number(a). If you use Number(a) in your code, you don't need to explain that much :) – elfan Sep 10 '19 at 02:46
13

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

Community
  • 1
  • 1
James Sumners
  • 14,485
  • 10
  • 59
  • 77
  • Erm, I answered the actual question: "Javascript not sorting correctly, what am I doing wrong?" That doesn't necessitate providing the correct sorting function. _That_ is in the linked documentation, which the OP clearly should read. – James Sumners Apr 02 '13 at 13:42