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 (a);
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, Digital sorting
Copy CodeThe code is as follows: Obj.sort (SortBy (' B ', false, parseint));
Console.log (obj);
2. Sorting strings
Copy CodeThe code is as follows: Obj.sort (SortBy (' B ', false, String));
Console.log (obj);
Second, JSON sort example 2
Copy CodeThe code is as follows:
var willsort = [
{
Name: ' Shangwenhe ',
AGE:25,
height:170
},
{
Name: ' Zhangsan ',
Age:31,
height:169
},
{
Name: ' Lisi ',
Age:31,
height:167
},
{
Name: ' Zhaowu ',
Age:22,
height:160
},
{
Name: ' Wangliu ',
Age:23,
height:159
}
];
/*
Sort JSON @function Jsonsort
JSON to sort @param json
Key values sorted @param key
*/
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);
Third, JSON sort 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 ');
JSON sort excerpt from Baidu