.sort() function will sort array of strings in JavaScript. We have an array of strings like var arr= ['ABC', 'XYX', 'BCD'] To sort this array, str.sort() will sort the array of string.
JavaScript sort function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="sortArray()">Sort the array</button>
<p id="sample"></p>
<script>
var arr= ['ABC', 'XYX', 'BCD'];
document.getElementById("sample").innerHTML = arr;
function sortArray() {
fruits.sort();
document.getElementById("sample").innerHTML = arr;
}
</script>
</body>
</html>
In this example, we are passing calculation as (b-a). function sortArray() { arr.sort(function(a, b){return b-a}); document.getElementById("sample").innerHTML = arr; } See the code snippet:
JavaScript sort function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="sortArray()">Sort the array</button>
<p id="sample"></p>
<script>
var arr= [36, 96, 3, 5, 35, 10];
document.getElementById("sample").innerHTML = arr;
function sortArray() {
arr.sort(function(a, b){return b-a});
document.getElementById("sample").innerHTML = arr;
}
</script>
</body>
</html>