2015-04-06 20 views
0

我有一个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) 
}); 

有没有办法通过双方的地位和头衔订购?因此,状态为“已下载”的所有人都按照标题进行分组和排序,然后按“未下载”并按标题排序。我也想“下载”成为第一个分隔线。

+1

您能否提供您想要的排序样本? ? – 2015-04-06 03:01:07

回答

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

+0

@janlindso抱歉,你的意思是? – 2015-04-06 03:14:15

0

因为'D''Downloaded''N'之前,从'Not downloaded'降临时,你可以做状态的标准字符串比较,其次是一个基于标题,如果他们是平等的。

if (a.status == b.status) { 
    return a.title.localeCompare(b.title); 
} else { 
    return a.status.localCompare(b.status); 
} 
0

我想你期待基础上,titlestatus列multisorting阵列上。如果是这样,以下将有所帮助。

的Comparer

var comparer = function(x,y){ 
       return x.localeCompare(y); 
       } 

装饰到obatin排序值

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将与statustitle排序的数组。而在上面的comparer,我还没有处理nullundefined值。排序也在ascending中执行。对于descending订单只是将排序比较结果乘以-1