The example in this article describes the sorting method for the JavaScript object array. Share to everyone for your reference, specific as follows:
The array sort function of JavaScript is sorted by default in ascending order of ASCII characters.
Arrayobj.sort (sortfunction);
Parameters: Sortfunction
Options available. is the name of the function used to determine the order of elements. If this argument is omitted, then the elements are sorted in ascending order in ASCII characters.
The sort method sorts the array object appropriately, and does not create a new array object during execution.
If you provide a function for the sortfunction parameter, the function must return one of the following values:
Negative value if the first argument passed is smaller than the second argument.
0 if two parameters are equal.
Positive value if the first argument is larger than the second argument.
The above method is easy to sort in one dimension, but how do you sort by the same multiple-key values as the order in SQL statements?
Multiple-key ordering of multidimensional arrays requires more complexity, but does not require a circular resolution. The truth of the actual solution is the same.
Digital:
The following example is to sort the multidimensional array of numbers by the order of the 5th, 9th, and 3rd columns, as in SQL statements by COL5,COL9,COL7. A number can be subtracted directly from two items, with the result as the return value.
<script language=javascript>
var myarray = new Array ();
for (Var i=0;i<10;i++) {
myarray[i]=new Array ();
Myarray[i][0]=math.floor (Math.random () *10);
Myarray[i][1]=math.floor (Math.random () *10);
Myarray[i][2]=math.floor (Math.random () *10);
Myarray[i][3]=math.floor (Math.random () *10);
Myarray[i][4]=math.floor (Math.random () *10);
Myarray[i][5]=math.floor (Math.random () *10);
Myarray[i][6]=math.floor (Math.random () *10);
Myarray[i][7]=math.floor (Math.random () *10);
Myarray[i][8]=math.floor (Math.random () *10);
Myarray.sort (
function (x, y) {
if (X[4]!=y[4]) {return
x[4]-y[4];
} else if (X[8]!=y[8]) {
return x[8]-y[8];
} else if (X[6]!=y[6]) {return
x[6]-y[6];
} else {return
1;
}
}
)
; for (Var i=0;i<myarray.length;i++) ... {
document.write (Myarray[i].join (",") + "<br/>");
}
</script>
Character:
character, items in sortfunction cannot be subtracted directly as numbers, and the Str1.localecompare (str2) method needs to be called to compare to satisfy the return value. The following is the case where the 1th, 2 columns of a multidimensional array are sorted.
function Sortfunction (array) {return
Array.Sort (function (x, y) ... {return
(x[0]==y[0])? (X[1].localecompare (y[1])):(X[0].localecompare (y[0])
});
Therefore, the sorting function of Arrayobject.sort (sortfunction) is still very powerful, and finally it can realize the function of order by as in SQL statement.
I hope this article will help you with JavaScript programming.