Intro
Sort is a prevalent topic in programing. Although the sort operation mostly is handled by the back-end like PHP, Java and so on, occasionaly some are occured in front-end. Here are some simple instances I dealt with recently.
Bubble-like Sort
Suppose some list elements ordered as follows:
1 | <ul id="demo"> |
Every time I filter through the nodes to get the smallest-value one from 1st one to 4nd one, and then I put it to the tail of lists. Next, I still filter to get the smallest-value one but from 1st one to 3nd one, and still put it to the tail to the lists. Now, two elements are sorted, and still two ones stay idle. The operation continues until all the elements have been sorted.
The produceres can be illustrated as follows:
2 1 4 3 -> 2 4 3 1 -> 4 3 1 2 -> 4 1 2 3 -> 1 2 3 4
The following is my code:
1 | var ulObj = document.getElementById('demo'); |
Pay attention to the part A and B.
- Part A: Due to the type of
lists[i].innerHTML
, sort order is according to the string Unicode code points. Therefore,parseInt()
function is expected! - Part B: This operation is optional. Because everytime
appendChild(node)
is invoked, it will remove the node from the orignal parent and then append it to the new parent. So removeChild() function can be dispensable.
Use Array.sort()
The first time, I applied the sort() method of Array as following:
1 | var ulObj = document.getElementById('demo'); |
However these measures are not accepted!
A node list may look like an array, but it is not. The node list can be looped through and referred to its nodes like an array. However, Array Methods are forbidden, like valueOf() or join() on the node list.
Therefore, I need to convert the list to a new array as initial. After sort()
method, the list elemnts are appended with appendChild()
method.
1 | var ulObj = document.getElementById('demo'); |
In part A, there is a custom compareFunctiom to define the sort order. Especially to deserve to be mentioned, elements are sorted by converting them to strings and comparing strings in Unicode point order by defaut. The parseInt()
can still not be erased.