JSON sort excerpt from Baidu

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.