我有一个JSON:
[{
"title": "title you desire",
"url" : "thisistheurl.com",
"status" : "Downloaded"
},{
"title": "title you desire",
"url" : "thisistheurl.com",
"status" : "Downloaded"
},{
"title": "title you desire",
"url" : "thisistheurl.com",
"status" : "Not downloaded"
}]
我有这个功能按标题排序:
array.sort(function (a, b) {
var nameA = a.status,
nameB = b.status;
if (nameA < nameB) //sort string ascending
return -1;
if (nameA > nameB)
return 1;
return 0; //default return value (no sorting)
});
有没有办法按地位和头衔订购?所有状态都是&#34; Downloaded&#34;有点分组并按标题排序,然后&#34;未下载&#34;并按标题排序。我也想&#34; Downloaded&#34;成为第一个分手。
答案 0 :(得分:0)
如果状态相同,则按标题排序,如
var array = [{
"title": "title you desire2",
"url": "thisistheurl.com",
"status": "Downloaded"
}, {
"title": "title you desire1",
"url": "thisistheurl.com",
"status": "Downloaded"
}, {
"title": "title you desire",
"url": "thisistheurl.com",
"status": "Not downloaded"
}];
function sortString(a, b) {
if (a < b) { //sort string ascending
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
array.sort(function (a, b) {
var status = sortString(a.status, b.status);
if (status == 0) {
return sortString(a.title, b.title);
}
return status;
});
console.log(array)
演示:Fiddle
答案 1 :(得分:0)
由于来自'D'
'Downloaded'
的{{1}}来自'N'
'Not downloaded'
,您可以对状态进行标准字符串比较,然后根据标题进行比较,如果它们相等
if (a.status == b.status) {
return a.title.localeCompare(b.title);
} else {
return a.status.localCompare(b.status);
}
答案 2 :(得分:0)
我认为您期望基于title
和status
列对阵列进行多分类。如果是这样,以下将有所帮助。
<强>的Comparer 强>
var comparer = function(x,y){
return x.localeCompare(y);
}
装饰者要遵守排序值
var getComparer = function(field,fn){
return function(x,y){
return fn(x[field],y[field]);
}
}
现在要在数组中按顺序排序字段。
var sorts = ["status","title"];
var arr = ArraytoSort;
for(var i=0; i < sorts.lenght; i++){
arr = arr.sort(getComparer(sorts[i],comparer))
}
现在arr
将使用status
和title
对数组进行排序。在上面comparer
中,我没有处理null
和undefined
值。排序也在ascending
中执行。对于descending
订单,只需将排序比较结果与-1