CancelImage Upload

How to sort a JavaScript Array alphabetically

Quite often when dealing with arrays the need arises to sort them alphabetically. In JavaScript this is accomplished via the function sort(), which can be called upon at the end of an array object:

yourArray = yourArray.sort();

Here an example of an array output, before and after it has been sorted in alphabetical order:

<title>How to sort a JavaScript Array alphabetically</title>
<script type="text/javascript">

function sortArray()

    //Returning the unsorted array:

    var fruits = new Array('Oranges', 'Pears', 'Bananas', 'Strawberries', 'Apples');

    var fruitsTogether = fruits.join(", ");

    document.getElementById("unSorted").innerHTML = fruitsTogether;

    //Sorting the array alphabetically:

    fruitsSorted = fruits.sort();

    fruitsTogether = fruitsSorted.join(", ");

    document.getElementById("sorted").innerHTML = fruitsTogether;


<body onload="javascript:sortArray();">

<div id="unSorted"></div>
<div id="sorted"></div>


Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •