Array.prototype.sort()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/sort
  • Revision title: Array sort method
  • Revision id: 524
  • Created:
  • Creator: dotnetCarpenter
  • Is current revision? No
  • Comment added what the method returns. Not sure how the design rules are for this kind of information but the info is freaking useful.; 12 words added

Revision Content

 

Summary

Sorts the elements of an array in place.

Returns the array being sorted. * Works across all browsers.

Method of Array
Implemented in: JavaScript 1.1
JavaScript 1.2: modified behavior.
ECMAScript Edition: ECMA-262 1st Edition

Syntax

array.sort([compareFunction])

Parameters

compareFunction 
Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

Description

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always returns the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

So, the compare function has the following form:

function compare(a, b)
{
  if (a is less than b by some ordering criterion)
     return -1;
  if (a is greater than b by the ordering criterion)
     return 1;
  // a must be equal to b
  return 0;
}

To compare numbers instead of strings, the compare function can simply subtract b from a:

function compareNumbers(a, b)
{
  return a - b;
}

Some implementations of JavaScript implement a stable sort: the index partial order of a and b does not change if a and b are equal. If a's index was less than b's before sorting, it will be after sorting, no matter how a and b move due to sorting.

Sort is stable in SpiderMonkey and all Mozilla-based browsers starting with Gecko 1.9 (see {{ Bug("224128") }}).

The behavior of the sort method changed between JavaScript 1.1 and JavaScript 1.2.

In JavaScript 1.1, on some platforms, the sort method does not work. This method works on all platforms for JavaScript 1.2.

In JavaScript 1.2, this method no longer converts undefined elements to null; instead it sorts them to the high end of the array. For example, assume you have this script:

var a = [];
a[0] = "Ant";
a[5] = "Zebra";

// assumes a print function is defined
function writeArray(x)
{
  for (i = 0; i < x.length; i++)
  {
    print(x[i]);
    if (i < x.length-1)
      print(", ");
  }
}

writeArray(a);
a.sort();
print("\n");
writeArray(a);

In JavaScript 1.1, JavaScript prints:

ant, null, null, null, null, zebra
ant, null, null, null, null, zebra

In JavaScript 1.2, JavaScript prints:

ant, undefined, undefined, undefined, undefined, zebra
ant, zebra, undefined, undefined, undefined, undefined

The sort() method can be conveniently used with closures

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
    return a - b;
});
print(numbers);

Examples

Example: Creating, displaying, and sorting an array

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function.

var stringArray = ["Blue", "Humpback", "Beluga"];
var numericStringArray = ["80", "9", "700"];
var numberArray = [40, 1, 5, 200];
var mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];

function compareNumbers(a, b)
{
  return a - b;
}

// again, assumes a print function is defined
print("stringArray: " + stringArray.join() +"\n");
print("Sorted: " + stringArray.sort() +"\n\n");

print("numberArray: " + numberArray.join() +"\n");
print("Sorted without a compare function: " + numberArray.sort() +"\n");
print("Sorted with compareNumbers: " + numberArray.sort(compareNumbers) +"\n\n");

print("numericStringArray: " + numericStringArray.join() +"\n");
print("Sorted without a compare function: " + numericStringArray.sort() +"\n");
print("Sorted with compareNumbers: " + numericStringArray.sort(compareNumbers) +"\n\n");

print("mixedNumericArray: " + mixedNumericArray.join() +"\n");
print("Sorted without a compare function: " + mixedNumericArray.sort() +"\n");
print("Sorted with compareNumbers: " + mixedNumericArray.sort(compareNumbers) +"\n\n");

This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback

numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200

numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700

mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700

See Also

join, reverse

{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/sort", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Array/sort", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/sort" } ) }}

Revision Source

<p> </p>
<h3 name="Summary">Summary</h3>
<p>Sorts the elements of an array in place.</p>
<p>Returns the array being sorted. * Works across all browsers.</p>
<table class="fullwidth-table"> <tbody> <tr> <td class="header" colspan="2">Method of <a href="/en/JavaScript/Reference/Global_Objects/Array" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></td> </tr> <tr> <td>Implemented in:</td> <td>JavaScript 1.1<br> JavaScript 1.2: modified behavior.</td> </tr> <tr> <td>ECMAScript Edition:</td> <td>ECMA-262 1st Edition</td> </tr> </tbody>
</table>
<h3 name="Syntax">Syntax</h3>
<p><code><em>array</em>.sort([<em>compareFunction</em>])</code></p>
<h3 name="Parameters">Parameters</h3>
<dl> <dt><code>compareFunction</code> </dt> <dd>Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.</dd>
</dl>
<h3 name="Description">Description</h3>
<p>If <code>compareFunction</code> is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.</p>
<p>If <code>compareFunction</code> is supplied, the array elements are sorted according to the return value of the compare function. If <code>a</code> and <code>b</code> are two elements being compared, then:</p>
<ul> <li>If <code>compareFunction(a, b)</code> is less than 0, sort <code>a</code> to a lower index than <code>b</code>.</li>
</ul>
<ul> <li>If <code>compareFunction(a, b)</code> returns 0, leave <code>a</code> and <code>b</code> unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.</li>
</ul>
<ul> <li>If <code>compareFunction(a, b)</code> is greater than 0, sort <code>b</code> to a lower index than <code>a</code>.</li>
</ul>
<ul> <li><code>compareFunction(a, b)</code> must always returns the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined</li>
</ul>
<p>So, the compare function has the following form:</p>
<pre class="brush: js">function compare(a, b)
{
  if (a is less than b by some ordering criterion)
     return -1;
  if (a is greater than b by the ordering criterion)
     return 1;
  // a must be equal to b
  return 0;
}
</pre>
<p>To compare numbers instead of strings, the compare function can simply subtract <code>b</code> from <code>a</code>:</p>
<pre class="brush: js">function compareNumbers(a, b)
{
  return a - b;
}
</pre>
<p>Some implementations of JavaScript implement a stable sort: the index partial order of <code>a</code> and <code>b</code> does not change if <code>a</code> and <code>b</code> are equal. If <code>a</code>'s index was less than <code>b</code>'s before sorting, it will be after sorting, no matter how <code>a</code> and <code>b</code> move due to sorting.</p>
<p>Sort is stable in <a href="/en/SpiderMonkey" title="en/SpiderMonkey">SpiderMonkey</a> and all Mozilla-based browsers starting with <a href="/en/Gecko" title="en/Gecko">Gecko</a> 1.9 (see {{ Bug("224128") }}).</p>
<p>The behavior of the <code>sort</code> method changed between JavaScript 1.1 and JavaScript 1.2.</p>
<p>In JavaScript 1.1, on some platforms, the <code>sort</code> method does not work. This method works on all platforms for JavaScript 1.2.</p>
<p>In JavaScript 1.2, this method no longer converts <a href="/en/JavaScript/Reference/Global_Objects/undefined" title="en/Core_JavaScript_1.5_Reference/Global_Properties/undefined">undefined</a> elements to <code>null</code>; instead it sorts them to the high end of the array. For example, assume you have this script:</p>
<pre class="brush: js">var a = [];
a[0] = "Ant";
a[5] = "Zebra";

// assumes a print function is defined
function writeArray(x)
{
  for (i = 0; i &lt; x.length; i++)
  {
    print(x[i]);
    if (i &lt; x.length-1)
      print(", ");
  }
}

writeArray(a);
a.sort();
print("\n");
writeArray(a);
</pre>
<p>In JavaScript 1.1, JavaScript prints:</p>
<pre class="eval">ant, null, null, null, null, zebra
ant, null, null, null, null, zebra
</pre>
<p>In JavaScript 1.2, JavaScript prints:</p>
<pre class="eval">ant, undefined, undefined, undefined, undefined, zebra
ant, zebra, undefined, undefined, undefined, undefined
</pre>
<p>The sort() method can be conveniently used with <a class="internal" href="/en/JavaScript/Guide/Closures" title="en/Core JavaScript 1.5 Guide/Working with Closures">closures</a>: </p>
<pre class="brush: js">var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
    return a - b;
});
print(numbers);
</pre>
<h3 name="Examples">Examples</h3>
<h4 name="Example:_Creating.2C_displaying.2C_and_sorting_an_array">Example: Creating, displaying, and sorting an array</h4>
<p>The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function.</p>
<pre class="brush: js">var stringArray = ["Blue", "Humpback", "Beluga"];
var numericStringArray = ["80", "9", "700"];
var numberArray = [40, 1, 5, 200];
var mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];

function compareNumbers(a, b)
{
  return a - b;
}

// again, assumes a print function is defined
print("stringArray: " + stringArray.join() +"\n");
print("Sorted: " + stringArray.sort() +"\n\n");

print("numberArray: " + numberArray.join() +"\n");
print("Sorted without a compare function: " + numberArray.sort() +"\n");
print("Sorted with compareNumbers: " + numberArray.sort(compareNumbers) +"\n\n");

print("numericStringArray: " + numericStringArray.join() +"\n");
print("Sorted without a compare function: " + numericStringArray.sort() +"\n");
print("Sorted with compareNumbers: " + numericStringArray.sort(compareNumbers) +"\n\n");

print("mixedNumericArray: " + mixedNumericArray.join() +"\n");
print("Sorted without a compare function: " + mixedNumericArray.sort() +"\n");
print("Sorted with compareNumbers: " + mixedNumericArray.sort(compareNumbers) +"\n\n");
</pre>
<p>This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.</p>
<pre class="eval">stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback

numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200

numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700

mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700
</pre>
<h3 name="See_Also">See Also</h3>
<p><a href="/en/JavaScript/Reference/Global_Objects/Array/join" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array/join">join</a>, <a href="/en/JavaScript/Reference/Global_Objects/Array/reverse" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Array/reverse">reverse</a></p>
<p>{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/Array/sort", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/Array/sort", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/Array/sort" } ) }}</p>
Revert to this revision