Javascript: Array.sort()

February 20, 2008 § Leave a comment

What is it?

It is a global function that’s a built-in of Array object.

Syntax:

Array.sort(comparisonFunction);

How to use sort():

  • If sort function is being used without comparisonFunction parameter, the values inside array will first be converted into string, and sorted lexically.
  • If sort function is used with comparisonFunction, it must return either 1, 0, or -1 depending on the comparison.

Here is a sample of comparisonFunction:

function compare(a, b)

{

if ( a < b ) { return -1; }

else if ( a > b ) { return 1; }

else () { return 0; }

}

Reference:

http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:sort

Advertisements

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

What’s this?

You are currently reading Javascript: Array.sort() at RAPD.

meta

%d bloggers like this: