Here we use the sorting function to sort the array and we would print the array and the position of the new element in the DOM.
- Create an empty array.
- Now make a sorting function by taking the parameter as an array.
- Now make an onClick function as whenever the button is pressed the function automatically runs.
- In the onClick function, we would first add the element to the array then find the position of the element by using the iterator function
- In finding the position we would see if the array element is greater than or not if yes then mark that position and break the loop.
- Now at the end, we would print the array and the position of the newly added element into the DOM.
sort() Function: This function takes an argument of the desired array to be sorted and implements the selection sort and gives us the sorted array as a result.
add() Function: This function is an on-click function and it is triggered when the button is clicked. This function takes the value from the input box and stores it into the sorted array and increments the array index value by one. Then this function finds the position of the newly added element in the sorted array by comparing it with every element of the array and if it finds the value greater than it then it breaks the loop and stores the index of that position and then it calls the sort() function to sort the array again. Finally, it gives output in the DOM
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.