/

HTML / CSS / JavaScript Tutorial

JavaScript Array method: sort()

[this page | pdf | back links]

The sort() method (when applied to a JavaScript array) sorts elements of the array.

 

By default, it sorts values as alphabetical strings in ascending order. This does not work well for numbers

 

It has the following syntax with the following parameters. It returns a new array containing the selected elements.

 

array.sort(comparefunction)

 

Parameter

Required / Optional

Description

comparefunction

Optional

A function that defines an alternative sort order, e.g. function(a,b){return a - b} to sort in ascending numerical order or function(a,b){return b - a} to sort in descending numerical order

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var h = ["a", "c", "b"];
document.getElementById("Example").innerHTML =
  'var h = ["a", "c", "b"];<br>' +
  'var x = h.sort();';
document.getElementById("Result").innerHTML = h.sort();
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArraySort() {
  var h = [1, 2, 3]; return !!h.sort;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays


Desktop view | Switch to Mobile