Home > Web Front-end > JS Tutorial > 3 examples of javascript sorting JSON data_javascript skills

3 examples of javascript sorting JSON data_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 16:52:27
Original
1137 people have browsed it

1. Suitable for numerical sorting and subtitle sorting
There are many json sorting methods, and this is the simplest one.

Copy code The 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(a);
b = primer(b);
}
if (a < b) { return rev * - ; ', c: 'c'},
{b: '1', c: 'a'},
{b: '2', c: 'b'}
];

1. Numeric sorting



Copy code

The code is as follows:obj.sort(sortBy('b ', false, parseInt));console.log(obj);2. String sorting

Copy code

2. JSON sorting example 2


Copy code

The 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
}
] ;


/*
@function JsonSort Sort 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);


3. JSON sorting example 3

Copy code

The 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 labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template