2015-04-06 49 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