0

today I found something interesting about array prototype sort.

var numbers = [1,7,23,11,50,60];

So I created an array of numbers and wanted to sort them. So I used

console.log(numbers.sort()) //-> [1, 11, 23, 50, 60, 7]

The result was weird, [1, 11, 23, 50, 60, 7]. What is wrong with the sort function?

var numbers = [1,7,23,11,50,60];
alert(numbers.sort())
Ahmet Can Güven
  • 5,392
  • 4
  • 38
  • 59
  • It seems to be a precise duplicate. The **reason** is that by default `sort` sorts elements as strings. The first answer to the duplicate question, in its very first sentence, states "By default the sort method sorts elements alphabetically.". –  Mar 05 '16 at 11:39
  • @torazaburo I just missed that line, sorry. Although I searched for any answers probably I didn't see it. – Ahmet Can Güven Mar 05 '16 at 11:42

2 Answers2

2

sort() will call toString() on all members and thus they get converted to string and you get the wrong sort order.

you'll have to manually pass a comparator.

function comparator(x,y) {
    return x - y;
}

numbers.sort(comparator);
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

If you want to sort by integer just do it like this. The compare Function of the normal sort converts the integer to string and then compares them.

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

var numArray = [1,7,23,11,50,60];
numArray.sort(sortNumber);

Output

[1, 7, 11, 23, 50, 60]
Kordi
  • 2,405
  • 1
  • 14
  • 13