-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?

2
  • 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 Commented Jul 4, 2015 at 3:30
  • @SumanLama A compare function is used as a callback; albeit not one that is invoked asynchronously. Commented Jul 4, 2015 at 4:02

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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).

3 Comments

What is "implementation defined"?
The implementation by Mozilla, for example. The official specification states it's implementation defined.
The implementation of the sort algorithm or the default ordering function?
0

Try like this

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

2 Comments

why the built-in sort do not support this by itself ?
By default the sort method sorts elements alphabetically but for numerically you have to add numeric comparer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.