Edit

JavaScript Sorting Arrays

Sorting is a common task when working with arrays. It would be used, for instance, if you want to display the city or county names in alphabetical order.

How to Sort of an Array

The sort() method is used to sorting array elements in alphabetical order.

Example of Code

<script>
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    var sorted = fruits.sort();    
    document.write(sorted);
</script>

Output

How to Reverse of an Array

The reverse() method is used to reverse the order of the elements of an array.

This method reverses an array in such a way that the first array element becomes the last, and the last array element becomes the first.

Example of Code

<script>
    var counts = ["one", "two", "three", "four", "five"];
    var reversed = counts.reverse(); 
    document.write(reversed);
</script>

Output

How to Sort of Numeric Arrays

The sort() method may produce unexpected result when it is applied on the numeric arrays (i.e. arrays containing numeric values).

Example of Code

<script>
    var numbers = [5, 20, 10, 75, 50, 100];
    numbers.sort(); // Sorts numbers array
    document.write(numbers); // Outputs: 10,100,20,5,50,75
</script>

Output

How to Find the Highest Array Value

There are no built-in functions for finding the max or min value in an array. However, after you have sorted an array, you can use the index to obtain the highest and lowest values.

Example of Code

<p id="highest-array-value"><p>
<script>
    var points = [40, 100, 1, 5, 25, 10];
    points.sort(function(a, b){return b-a});
    document.getElementById("highest-array-value").innerHTML = points[0];
</script>

Output

How to Find the Lowest Array Value

Example of Code

<p id="lowest-array-value"><p>
<script>
    var point = [40, 100, 1, 5, 25, 10];
    point.sort(function(a, b){return a-b});
    document.getElementById("lowest-array-value").innerHTML = point[0];
</script>

Output