Array.sort() : Sort « Array « JavaScript Tutorial

Home
JavaScript Tutorial
1.Language Basics
2.Operators
3.Statement
4.Development
5.Number Data Type
6.String
7.Function
8.Global
9.Math
10.Form
11.Array
12.Date
13.Dialogs
14.Document
15.Event
16.Location
17.Navigator
18.Screen
19.Window
20.History
21.HTML Tags
22.Style
23.DOM Node
24.Drag Drop
25.Object Oriented
26.Regular Expressions
27.XML
28.GUI Components
29.Dojo toolkit
30.jQuery
31.Animation
32.MS JScript
JavaScript Tutorial » Array » Sort 
11.29.1.Array.sort()

Syntax

array.sort()
    array.sort(function)

The sort() method rearranges the elements of the array based on a sorting order.

If the method has no parameters, JavaScript attempts to convert all the elements of the array to strings and then sort them alphabetically.

If the array should be sorted some other way, a function must be provided to handle the new sorting algorithm.

The function specified must operate based on the following rules:

The function must accept two arguments that are to be compared.

The function must return a number indicating the order of the two arguments in relation to each other.

If the first argument should appear before the second argument, a number less than zero should be returned from the function.

If the first argument should appear after the second argument, a number greater than zero should be returned from the function.

If both arguments are equivalent, zero should be returned from the function.

The following example sorts Array Based on Argument Lengths

<html>
    <script language="JavaScript">
    <!--
    function contentsOfArray(theArray)
    {
      document.write("the array contains:<br>");
      for(i=0; i<theArray.length; i++)
      {
        document.write("Position ",i," = ",theArray[i],"<br>");
      }
    }
    function sortOnArgLen(arg1,arg2)
    {
      if(arg1.length < arg2.length)
        return -1;
      if(arg1.length > arg2.length)
        return 1;
      if(arg1.length == arg2.length)
        return 0;
    }
    shapes = new Array("A","B","C");
    document.write("Before the sort method ");
    contentsOfArray(shapes);
    shapes.sort(sortOnArgLen);
    document.write("<br>After the sort method ");
    contentsOfArray(shapes);
    --></script>
    </html>
11.29.Sort
11.29.1.Array.sort()
11.29.2.Sort a string array
11.29.3.Array.sort is case sensitive
11.29.4.Using the sort() method on numbers and strings
11.29.5.Array.sort() with custom sorter
11.29.6.Using an alphabetical sort() method on strings
11.29.7.Using the sort() method on numbers and strings with custom sorter
11.29.8.Case-insensitive comparison
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.