mozilla

Revision 511 of Array.prototype.sort()

  • Revision slug: JavaScript/Reference/Global_Objects/Array/sort
  • Revision title: Array sort method
  • Revision id: 511
  • Created:
  • Creator: H3h
  • Is current revision? No
  • Comment /* Example: Creating, displaying, and sorting an array */ More 21st century good practices

Revision Content

Summary

Sorts the elements of an array.

Method of Array
Implemented in: JavaScript 1.1, NES 2.0

JavaScript 1.2: modified behavior.

ECMA Version: ECMA-262

Syntax

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, 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 {{template.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:

<script>
var a = [];
a[0] = "Ant";
a[5] = "Zebra";

function writeArray(x) {
   for (i = 0; i < x.length; i++) {
      document.write(x[i]);
      if (i < x.length-1) document.write(", ");
   }
}

writeArray(a);
a.sort();
document.write("<br>");
writeArray(a);
</script>

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.

<script>
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;
}

document.write("<p>stringArray: " + stringArray.join() +"<br>");
document.write("Sorted: " + stringArray.sort() +"</p>");

document.write("<p>numberArray: " + numberArray.join() +"<br>");
document.write("Sorted without a compare function: " + numberArray.sort() +"<br>");
document.write("Sorted with compareNumbers: " + numberArray.sort(compareNumbers) +"</p>");

document.write("<p>numericStringArray: " + numericStringArray.join() +"<br>");
document.write("Sorted without a compare function: " + numericStringArray.sort() +"<br>");
document.write("Sorted with compareNumbers: " + numericStringArray.sort(compareNumbers) +"</p>");

document.write("<p>mixedNumericArray: " + mixedNumericArray.join() +"<br>");
document.write("Sorted without a compare function: " + mixedNumericArray.sort() +"<br>");
document.write("Sorted with compareNumbers: " + mixedNumericArray.sort(compareNumbers) +"</p>");
</script>

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

{{ wiki.languages( { "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.
</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>
<p><code>
sort(<i>compareFunction</i>)
</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>
<p>So, the compare function has the following form:
</p>
<pre>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>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">SpiderMonkey</a> and all Mozilla-based browsers starting with <a href="en/Gecko">Gecko</a> 1.9 (see {{template.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 undefined elements to null; instead it sorts them to the high end of the array. For example, assume you have this script:
</p>
<pre>&lt;script&gt;
var a = [];
a[0] = "Ant";
a[5] = "Zebra";

function writeArray(x) {
   for (i = 0; i &lt; x.length; i++) {
      document.write(x[i]);
      if (i &lt; x.length-1) document.write(", ");
   }
}

writeArray(a);
a.sort();
document.write("&lt;br&gt;");
writeArray(a);
&lt;/script&gt;
</pre>
<p>In JavaScript 1.1, JavaScript prints:
</p>
<pre>ant, null, null, null, null, zebra
ant, null, null, null, null, zebra
</pre>
<p>In JavaScript 1.2, JavaScript prints:
</p>
<pre>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>&lt;script&gt;
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;
}

document.write("&lt;p&gt;stringArray: " + stringArray.join() +"&lt;br&gt;");
document.write("Sorted: " + stringArray.sort() +"&lt;/p&gt;");

document.write("&lt;p&gt;numberArray: " + numberArray.join() +"&lt;br&gt;");
document.write("Sorted without a compare function: " + numberArray.sort() +"&lt;br&gt;");
document.write("Sorted with compareNumbers: " + numberArray.sort(compareNumbers) +"&lt;/p&gt;");

document.write("&lt;p&gt;numericStringArray: " + numericStringArray.join() +"&lt;br&gt;");
document.write("Sorted without a compare function: " + numericStringArray.sort() +"&lt;br&gt;");
document.write("Sorted with compareNumbers: " + numericStringArray.sort(compareNumbers) +"&lt;/p&gt;");

document.write("&lt;p&gt;mixedNumericArray: " + mixedNumericArray.join() +"&lt;br&gt;");
document.write("Sorted without a compare function: " + mixedNumericArray.sort() +"&lt;br&gt;");
document.write("Sorted with compareNumbers: " + mixedNumericArray.sort(compareNumbers) +"&lt;/p&gt;");
&lt;/script&gt;
</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>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>{{ wiki.languages( { "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