Array.prototype.sort()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/sort
  • Revision title: Array sort method
  • Revision id: 515
  • Created:
  • Creator: Trinithis
  • Is current revision? No
  • Comment Fixed flawed compare algorithm

Revision Content

Summary

Sorts the elements of an array in place.

Method of Array
Implemented in: JavaScript 1.1, NES 2.0

JavaScript 1.2: modified behavior.

ECMA Version: ECMA-262

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.

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, you should not subtract the numbers because this can cause overflow. For example, 9e307-(-9e307) equals Number.POSITIVE_INFINITY but so does 9e307-(-9.9e307). Following the same general compare form, one achieves a compare function that works on any numeric level:

function compareNumbers(a, b) {
  if(a > b)
    return 1;
  if(a < b)
    return -1;
  return 0;
}

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

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>
<table class="fullwidth-table">
<tbody><tr>
<td class="header" colspan="2">Method of <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></td>
</tr>
<tr>
<td>Implemented in:</td>
<td>JavaScript 1.1, NES 2.0
<p>JavaScript 1.2: modified behavior.
</p>
</td>
</tr>
<tr>
<td>ECMA Version:</td>
<td>ECMA-262</td>
</tr>
</tbody></table>
<h3 name="Syntax"> Syntax </h3>
<pre class="eval"><i>array</i>.sort(<i>compareFunction</i>);
</pre>
<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>
<p>So, the compare function has the following form:
</p>
<pre class="eval">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, you should not subtract the numbers because this can cause overflow. For example, <code>9e307-(-9e307)</code> equals <code>Number.POSITIVE_INFINITY</code> but so does <code>9e307-(-9.9e307)</code>. Following the same general compare form, one achieves a compare function that works on any numeric level:
</p>
<pre class="eval">function compareNumbers(a, b) {
  if(a &gt; b)
    return 1;
  if(a &lt; b)
    return -1;
  return 0;
}
</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">SpiderMonkey</a> and all Mozilla-based browsers starting with <a href="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/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="eval">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>
<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="eval">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");
</pre>
<pre class="eval">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/Core_JavaScript_1.5_Reference/Objects/Array/join">join</a>, <a href="en/Core_JavaScript_1.5_Reference/Objects/Array/reverse">reverse</a>
</p>
<div class="noinclude">
</div>
{{ 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" } ) }}
Revert to this revision