This article describes how to sort Json data by a Field Based on JavaScript. For more information, see
I. first introduce the built-in sort () method in js.
By default, this method sorts the elements in the array in alphabetical order. More precise, the elements are sorted in character encoding order.
Take the following example:
When the elements in the array are numeric, the sorting result is completely different from what we imagine, because the sorting is performed by default in the character encoding order.
Solution: the sort () method receives an optional parameter (this parameter must be a function). We can define the sorting rules by ourselves, as shown in figure
II. Specific implementation of json sorting
/** @ Description sorts the json array Based on a field * @ param array the json array object to be sorted * @ param field sorting field (this parameter must be a string) * @ param reverse order (false by default) * @ return array returns the sorted json array */function jsonSort (array, field, reverse) {// The array length is less than 2 or no sorting field is specified or if (array. length <2 |! Field | typeof array [0]! = "Object") return array; // number type sorting if (typeof array [0] [field] = "number") {array. sort (function (x, y) {return x [field]-y [field]});} // string type sorting if (typeof array [0] [field] = "string") {array. sort (function (x, y) {return x [field]. localeCompare (y [field])});} // reverse order if (reverse) {array. reverse ();} return array ;}
PS: JS: json object array sorted by object attribute
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 = (order == '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 the sort method, which can be used to specify the sorting function. Therefore, a sorting function can be dynamically generated to sort by specified object attributes;
Note: The original array sequence will change after sort !!