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"];
fruits.sort();

After the sorting, the result will be

Apple,Banana,Mango,Orange,芒果

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];
points.sort();

we got result:

0.88,1,10,100,25,40,5

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.

Example:

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 http://www.w3schools.com)

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:

0.88,1,5,10,25,40,100

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

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s