Array sort() Method - Javascript Array

Javascript examples for Array:sort

Description

The sort() method sorts the items of an array.

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

This method changes the original array.

Syntax

array.sort(compareFunction)

Parameter Values

Parameter Description
compareFunction Optional. A function that defines an alternative sort order.

The function should return a negative, zero, or positive value, depending on the arguments, like:

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

Return Value:

The Array object, with the items sorted

The following code shows how to Sort an array in descending order

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
var fruits = ["a","b","c","d","e"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {//from ww  w  .  j  a  v a  2s.c o  m
    fruits.sort();
    fruits.reverse();
    document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Related Tutorials