The following example code demonstrates How to Sort an Array of Elements Using JavaScript.

Basically, in this example, we use Bubble Sort to sort an array of elements. To begin with, first we create an array of ten elements. Also, note that, we have three buttons on the page. When user clicks on the first button, its event handler is called. In order to input elements, it executes a for loop that iterates 10 times to accept 10 numbers from the user. The values entered by the user are converted to numeric values using the Number() function.

Similarly, the second button calls a function that displays these values. While, the third button calls a function named sortElements() that perform bubble sort and displays the sorted array in another paragraph.

``````<html>
<title>Sorting in JavaScript</title>
<script>
arr=Array(10);
function sortElements(x)
{
str="Sorted Elements: ";
var n=10;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(i=0;i<10;i++)
{
str+=arr[i]+"  ";
}
var x=document.getElementById('d2');
x.innerHTML+=str;
}
function inputElements()
{
for(i=0;i<10;i++)
{
arr[i]=Number(prompt('Enter Element '+(i+1)));

}
}
function displayElements()
{
var str="";
for(i=0;i<10;i++)
{
str+=arr[i]+"  ";
}
var x=document.getElementById('d1');
x.innerHTML+=str;
}
</script>
<style>
div{
margin: 100px;
border: 2px black solid;
text-align: center;
}
</style>
<body>
<div>
<button onclick="inputElements()">Input Elements</button>
<button onclick="displayElements()">Display Elements</button>
<button onclick="sortElements()">Sort Elements</button>
<p id="d1">Original Array: </p>
<p id="d2"></p>
</div>
</body>
</html>``````

Output

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

Understanding JSON Web Tokens

Understanding HTTP Requests and Responses

Princites