Three examples of sorting JSON data by javascript

Source: Internet
Author: User

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 ');

Related Article

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.