3 Example(s) of JavaScript sort function


Description :

.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>

Output

Description :

arr.sort() function accept function as optional argument for sorting. Here is how it sort the array in asc order.

arr.sort(function(a, b) { return a - b; })


JavaScript sort function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<script>
var arr= [4, 2, 5, 1, 3];
arr.sort(function(a, b) {
  return a - b;
});
document.write(arr);
</script>
</body>
</html>

Output

Description :

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>

Output