Recently, projects in the group need a simple Table sorting function, which is easy to implement and there are a lot of off-the-shelf code on the Internet, so the task is quickly completed. However, during a cross-browser test, a problem was found in the chrome browser. The tester found that, when sorting by a column in chrome, if the sorting values of the two rows are the same, chrome will not change the order of the two columns as usual, but will change them in order. After a google question, we found that the original ECMAscript specification did not specify a specific sort algorithm, so each browser has its own sort algorithm, however, some vendors implement the Sorting Algorithm Based on unstable sorting algorithms, such as those before chrome and Mozilla/Firefox 3.0, but IE is a stable sorting algorithm. The differences in the implementation of this algorithm also result in inconsistent results of charts displayed in different browsers.
: The number on the left of the array indicates the order of initialization.
After thinking about it, I and another member in the Group gave their own solutions. His opinion is to implement specific sort algorithms to achieve unified control, given that there are many ready-made sorting algorithms on the Internet and the sorting algorithms are the foundation of programmers, this method is not complicated, and the only task is the implementation of code. However, I think there is actually a simpler method, because our data is parsed from xml based on XSLT, XSLT knows the serial number of each row of data (of course, it is easy to obtain this value if the server-side code reads data from the database or webservice ), so I think you can add an Index attribute for each column in XSLT, e.g. the first row Index = 1, the second row Index = 2... in this way, if two values are the same when sort is compared, the row number is compared. In this way, you only need to add two lines of code to the comparison function. The following is the implementation code and result:
The Code is as follows:
Var array = [
{Index: 1, val: 25 },
{Index: 2, val: 25 },
{Index: 3, val: 45 },
{Index: 4, val: 78}];
Array. sort (function (a, B ){
If (a. val = B. val ){
// If the two values are the same, they are compared based on the row number (index value during initialization.
Return a. Index-B. Index;
}
Return a. val-B. val;
})
For (var I = 0; I <array. length; I ++ ){
Document. write ("
"+ Array [I]. Index +": "+ array [I]. val +"
");
}
Updated results:
Of course, this is only one of the solutions. My goal is to minimize the amount of code we need to maintain, so as to minimize bugs. I hope it will be helpful to you.
Frustration is like a wall that forces us to prove to ourselves how eager we are to get the treasure behind it