Javascript Sorting array values as strings or numbers?

In Javascript, we use Array sort() Method to sort the items in an array alphabetically.

for example

var fruits = ["芒果","Banana", "Orange", "Apple", "Mango"];

After the sorting, the result will be


If we want to reverse the order (descending), then the easy way to do is call reverse() method. But for numbers, it’s still sorting alphabetically, like

var points = [40, 100, 1, 5, 25, 10, 0.88];

we got result:


Which actually we don’t expect, how can we let it sort numerically? Sort() method provided compareFunction as optional parameter.

A function that defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments, like:

  • function(a, b){return a-b}

When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.


When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100. (source from

Now we can use this argument function to sort numbers.

var points = [40, 100, 1, 5, 25, 10, 0.88];
points.sort(function(a, b){return a-b});

And new result comes:


if you want sort numbers in descending order, just change “return a-b” to “return b-a”.


About qianggan

Sr. Software Engineer
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s