First, we introduce the sort () method built in JS.
By default, this method sorts the elements in an alphabetical array, more precisely, by the order of character encoding.
See the following example:
When an element in an array is a numeric type, the result of the order is completely different from what we think, because the default is sorted in character-encoded order.
Solution: the sort () method receives an optional argument (this parameter must be a function), and we can define the collation ourselves, as shown in the following figure
Two. The specific implementation of JSON ordering
* * @description to sort the JSON array based on a field
* @param array The JSON array object to sort
* @param field Sort field (this parameter must be a string)
* @param Reverse whether reverse (default is False)
* @return array Returns the sorted JSON array
* *
function Jsonsort (array, field, reverse) {
//array length less than 2 or no sort field specified or not JSON format data
if (Array.Length < 2 | | |!fi eld | | typeof Array[0]!== "Object") return array;
Numeric type sort
if (typeof array[0][field] = = "Number") {
Array.Sort (function (x, y) {return X[field]-y[field]}); c21/>}
//String type sort
if (typeof array[0][field] = = "string") {
Array.Sort (function (x, y) {return X[field]. Localecompare (Y[field])});
Reverse
if (reverse) {
array.reverse ();
}
return array;
}
PS:JS: JSON object array sorted by object property
var array = [
{name: ' A ', phone:1},
{name: ' B ', phone:5},
{name: ' d ', phone:3},
{name: ' C ', phone:4}
]
array.sort (getsortfun (' desc ', ' phone '));
function Getsortfun (order, sortby) {
var Ordalpah = = (= = ' ASC ')? ' > ': ' < ';
var sortfun = new Function (' A ', ' B ', ' return a. ' + sortby + ordalpah + ' B. ' + SortBy + '? 1:-1 ');
return sortfun;
}
Alert (json.stringify (array));
The array itself has a sort method that specifies the sorting function, so you can dynamically generate a sort function to complete the need to sort by the specified object's attributes;
Note: The original array sequence will change after sort!!