【问题标题】:sorting an object respectively array effectively with jquery使用jquery有效地对对象分别进行排序
【发布时间】:2011-11-24 10:55:08
【问题描述】:

我对如何使用 jQuery 最有效地对以下数据进行排序很感兴趣:

我从服务器检索到一个 json 对象:

var data = {/*json-object*/};
$.each(data.level1.sub1, function(){
    if(this.name.length < 2) {
        this.type = "banana";
        itemarray.push(this);
    }
    else {
        this.type = "apple";
        itemarray.push(this);
    }
});

$.each(data.level2.sub1, function(){
    this.type = "kiwi";
    itemarray.push(this);
});

这让我明白我可以通过这样做列出数组中的内容(这是typeof 对象,而不是“真实”数组):

if (itemarray.length){
    $.each(itemarray, function(index, value){
      $('#wrapper').append('<li>' + index + ' : ' + value.name + ' * ' + value.type + '</li>');
    });
}  

结果:

0 : abc * apple
1 : a * banana
2 : lala * apple
3 : bcd - Copy * kiwi
4 : okl * banana

现在我想对数组(又是typeof 对象)进行排序:按类型分组并按类型对asc 进行排序。你会如何建议这样做?

【问题讨论】:

    标签: jquery arrays sorting


    【解决方案1】:

    由于您使用的是itemarray.push 方法,我假设itemarray 是一个真正的数组。数组对象(注意:typeof [] === "object")支持sort() 方法。

    使用原生的Array.sort方法,结合一个函数,如下图。该方法直接修改数组。

    var itemarray = [{type:"C"},{type: "B"}]; //Your array looks like this
    
    //ASC result: [{type:"C"}, {type:"B"}]
    itemarray.sort(function(x,y){
        return x.type.localeCompare(y.type);
    });
    //DESC result: [{type:"B"}, {type: "B"}]
    itemarray.sort(function(x,y){
        return y.type.localeCompare(x.type);
    });
    

    【讨论】:

    • 嘿,罗伯,到目前为止非常感谢。你的排序要么把我带到:0 : aname * apple 1 : bname * apple 2 : cname * apple 3 : aname * banana 4 : bname * banana 2 : aname * kiwi 3 : bname * kiwi 当我处理第一个排序方法两次(x.type.localeCompare(y.type) 而不是相反),这很好,因为它对每个类型和名称进行排序。但我实际上想要订单:苹果,猕猴桃,香蕉!我尝试了一些组合,但 sort() 会自行对类型名称进行排序 - 那么我怎样才能做到这一点呢?
    • 好的,明白了:按所需顺序对类型组进行分组,我在排序后执行以下操作:applearray = $.grep(itemarray, function(n, i){ return (n.type==="apple"); }); bananaarray = $.grep(itemarray, function(n, i){ return (n.type==="banana"); }); kiwiarray = $.grep(itemarray, function(n, i){ return (n.type==="kiwi"); }); itemarray=applearray.concat(kiwiarray).concat(bananarray);
    【解决方案2】:

    这样使用

    $(document).ready(function () {
      var data = {/*json-object*/};      
             ;
      data = data.sort(function (a, b) {
        if (a.type < b.type) { return -1 };
        if (a.type > b.type) { return 1 };
        return 0;
      });
      $.each(data, function (index, value) {
        $("#wrapper").append("<li>" + value.index + " : " + value.name + " * " + value.type + "</li>");
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 1970-01-01
      • 2021-09-11
      • 2014-09-27
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 2021-03-14
      相关资源
      最近更新 更多