I. Applicable to numerical sorting and Subtitle sorting
There are many sorting methods for json, which is the simplest one.
Copy codeThe Code is as follows:
Var sortBy = function (filed, rev, primer ){
Rev = (rev )? -1: 1;
Return function (a, B ){
A = a [filed];
B = B [filed];
If (typeof (primer )! = 'Undefined '){
A = primer ();
B = primer (B );
}
If (a <B) {return rev *-1 ;}
If (a> B) {return rev * 1 ;}
Return 1;
}
};
Var obj = [
{B: '3', c: 'C '},
{B: '1', c: 'A '},
{B: '2', c: 'B '}
];
1. digit sorting
Copy codeThe Code is as follows: obj. sort (sortBy ('B', false, parseInt ));
Console. log (obj );
2. String sorting
Copy codeThe Code is as follows: obj. sort (sortBy ('B', false, String ));
Console. log (obj );
Ii. JSON sorting Example 2
Copy codeThe Code is as follows:
Var willSort = [
{
Name: 'shanghai ',
Age: 25,
Height: 170
},
{
Name: 'hangsan ',
Age: 31,
Height: 169
},
{
Name: 'lisi ',
Age: 31,
Height: 167
},
{
Name: 'zhaowu ',
Age: 22,
Height: 160
},
{
Name: 'wangliu ',
Age: 23,
Height: 159
}
];
/*
@ Function JsonSort sorts json
@ Param json: json used for sorting
@ Param key: key value for sorting
*/
Function JsonSort (json, key ){
// Console. log (json );
For (var j = 1, jl = json. length; j <jl; j ++ ){
Var temp = json [j],
Val = temp [key],
I = J-1;
While (I> = 0 & json [I] [key]> val ){
Json [I + 1] = json [I];
I = I-1;
}
Json [I + 1] = temp;
}
// Console. log (json );
Return json;
}
Var json = JsonSort (willSort, 'age ');
Console. log (json );
Iii. JSON sorting Example 3
Copy codeThe Code is as follows:
Var people = [
{
Name: 'a75 ',
Item1: false,
Item2: false
},
{
Name: 'z32 ',
Item1: true,
Item2: false
},
{
Name: 'e77 ',
Item1: false,
Item2: false
}];
Function sortByKey (array, key ){
Return array. sort (function (a, B ){
Var x = a [key]; var y = B [key];
Return (x <y )? -1: (x> y )? 1: 0 ));
});
}
People = sortByKey (people, 'name ');