Three examples of javascript sorting JSON data

  • 2020-03-30 02:39:25
  • OfStack

1. It is suitable for numerical sorting and subtitle sorting
There are many ways to sort json, and this is the simplest of them all.


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. Numerical sorting
obj.sort(sortBy('b', false, parseInt));
console.log(obj);

2. String sorting
obj.sort(sortBy('b', false, String));
console.log(obj);


JSON sort example 2


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 right json The sorting
    @param        json     To sort json
    @param        key      Sort the key value
*/
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);

JSON sort example 3


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

PS: about json operation, here again for you to recommend a few more practical json online tools for your reference:

Online JSON code verification, verification, beautification, formatting tools:
(link: http://tools.jb51.net/code/json)

JSON online formatting tool:
(link: http://tools.jb51.net/code/jsonformat)

Online XML/JSON interconversion tool:
(link: http://tools.jb51.net/code/xmljson)

Json code online formatting/beautification/compression/editing/conversion tools:
(link: http://tools.jb51.net/code/jsoncodeformat)

Online json compression/escape tool:

(link: http://tools.jb51.net/code/json_yasuo_trans)

C language style /HTML/CSS/json code format beautification tool:
(link: http://tools.jb51.net/code/ccode_html_css_json)


Related articles: