gpt4 book ai didi

jquery - 使用jquery有效地对对象和数组进行排序

转载 作者:行者123 更新时间:2023-12-01 05:03:07 25 4
gpt4 key购买 nike

我对如何使用 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 排序。您建议如何这样做?

最佳答案

由于您使用的是 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);
});

关于jquery - 使用jquery有效地对对象和数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8255890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com