2. Sorting an Array
In order to
sort an array, the sort() method is used. Using this method, elements in the
array are arranged alphabetically.
For example:
<script>
var region12 = ["South Cotabato", "Cotabato City", "Sultan Kudarat",
"Sarangani", "General Santos City"];
region12.sort(); //sorts the array alphabetically
console.log(region12);
</script>
With the example above, it will print ["Cotabato City", "General Santos City", "Sarangani", "South Cotabato", "Sultan Kudarat"]. It is rearranged in an alphabetical order. If you want to reverse the output, the reverse() method can be used.
For example:
<script>
var region12 = ["South Cotabato", "Cotabato City", "Sultan Kudarat",
"Sarangani", "General Santos City"];
region12.sort(); //sorts the array alphabetically
region12.reverse(); //reverses the sorted array
console.log(region12); //prints ["Sultan Kudarat", "South Cotabato",
"Sarangani", "General Santos City", "Cotabato City"]
</script>