网站前端开发吧 关注:41贴子:211
  • 4回复贴,共1

对json进行排序

只看楼主收藏回复

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 对json排序
@param json 用来排序的json
@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;
JsonSort(willSort,'height');


IP属地:北京1楼2013-05-28 12:08回复


    IP属地:北京2楼2013-05-28 12:09
    回复
      2025-11-19 23:29:38
      广告
      不感兴趣
      开通SVIP免广告
      var jsonObjSort = { 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 } ], JsonSort:function(json,key){ 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; } return json; }};
      jsonObjSort.JsonSort(this.willSort,'age');jsonObjSort.JsonSort(this.willSort,'height');


      3楼2013-06-07 13:16
      回复
        var SortFn = {
        numArr : [0,54,76,2312,678,345,56,12,8,890,243,12,67,98,4],
        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 }
        ],
        sortObj: function(arr){
        for(var i=1,l=arr.length;i<l;i++){
        var temp = arr[i],j=i-1;
        if(arguments.length>1){
        var key = arguments[arguments.length-1],val = temp[key];
        while(j>=0&&arr[j][key]>val){
        arr[j+1] = arr[j];
        j--;
        }
        }else{
        while(j>=0&&arr[j]>temp){
        arr[j+1]=arr[j];
        j--;
        }
        }
        arr[j+1] = temp;
        }
        return arr;
        }};
        SortFn.sortObj(SortFn.numArr);
        SortFn.sortObj(SortFn.willSort,'age');
        SortFn.sortObj(SortFn.willSort,'height');


        4楼2013-06-07 14:34
        回复
          a 看了下,对key值为字符串的字母排序如何弄


          IP属地:北京5楼2013-10-16 09:35
          回复