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:

<html>
<head>
<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;

}

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

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

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com