-1

I'm new to javascript. I know it's a weakly typed language which the sort function can sort all type of objects.

but when it sort a array like

> var a = [1, 43, 2, 09, 23]
< undefined
> a.sort()
< [1, 2, 23, 43, 9]

only by the first number? what's the zen of this design?

so if I wanna sort a pure list which only contain numbers(bigger than 9), I must write a call-back function to accomplish this?

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Sinux
  • 1,728
  • 3
  • 15
  • 28
  • 1
    it does not just support 0 to 9. It sorts things in alphabetical order. So 100 comes before 2. And that is not a callback it is called a compare function – Suman Lama Jul 04 '15 at 03:30
  • @SumanLama A compare function *is* used as a [callback](https://en.wikipedia.org/wiki/Callback_(computer_programming)); albeit not one that is invoked asynchronously. – user2864740 Jul 04 '15 at 04:02

3 Answers3

1

If callback not specified, the array is sorted in lexicographical order:

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

stdob--
  • 28,222
  • 5
  • 58
  • 73
1

The default sorting method considers the array elements as strings, regardless of their type:

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

According to the official ECMAScript specification, this is actually implementation defined (http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11).

Jongware
  • 22,200
  • 8
  • 54
  • 100
0

Try like this

a.sort(function(a,b){return a-b;})
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80