I am wondering what is the most efficient way to insert an element (in this case a string) into its correct alphabetical order, with ONLY JavaScript (and not jQuery)? I thought that sorting the list immediately after inserting the item would be enough, but it does not work. I get the value that needs to be inserted through the value entered in the text box.
Before inserting a new item, the list is as follows:
- Albatross
- Fantasy
- Kea
- Kiwi
- takache
- Tui
If I want to add "Bellbird" to this list, I expect the list to now look:
- Albatross
- Bellbird
- Fantasy
- Kea
- Kiwi
- takache
- Tui
Here is the code that I use to try to achieve the desired result:
HTML:
<ul id="birds"> <li>Albatross</li> <li>Fantail</li> <li>Kea</li> <li>Kiwi</li> <li>Takahe</li> <li>Tui</li> </ul> <p><label for="addNewBirdField">Add new bird: </label> <input type="text" id="addNewBirdField" /></p> <p><button id ="addItem">Add new bird</button></p>
JavaScript:
function addNewBird() { var birdList = document.getElementById("birds"); //get birds unordered list var newBirdItem = document.createElement("li"); // create new li element var bird = document.getElementById("addNewBirdField").value // get data from form field var birdValue = document.createTextNode(bird); // create new textNode with value from previous step newBirdItem.appendChild(birdValue); // append textNode from previous step to li element (newBirdItem) birdList.appendChild(newBirdItem); // append li element to bird list birdList.sort(); } var addItem = document.getElementById("addItem"); addItem.onclick = addNewBird;
I looked at this link when sorting arrays (based on my programming knowledge, I assume that each element of the list is in an array), I understand what lexicographic sorting is - I found out about it this week.
If someone can help me with this, he would be very grateful.
source share