sort() method is used for sorting the items of an array.It sorts the values as strings in alphabetical and ascending order.
And sort() method sort alphabetic or numeric.
you can take reference of bellow example.
<!DOCTYPE html>
<html>
<body>
<!-- here write a button to sort the array -->
<button onclick="myFunction()">Click To sort</button>
<!-- here define a id -->
<p id="sort"></p>
<script>
//here define a variable of empname
var empname = ["Joe", "Roy", "Mac", "Carlo"];
document.getElementById("sort").innerHTML = empname;
//here write a function to call sort() method
function myFunction() {
empname.sort();
document.getElementById("sort").innerHTML = empname;
}
</script>
</body>
</html>
output will come following:
Carlo,Joe,Mac,Roy
Because sort() method sorts the values as strings in alphabetical.
0 Comment(s)