2013-02-21 57 views
1

我想按alphbatical順序對項目進行排序。不過,我也想分類項目類型。如何爲數組排序2種類型的值?

例如:

我想

type  sortValue 

blockItem a test1 
blockItem a test2 
blockItem b test3 
imageItem a image 
imageItem b image 
imageItem c image 
imageItem s image 
textItem a text 
textItem b text 
textItem c text 

我的代碼會做這樣的事情。

type  sortValue 

blockItem a test1 
blockItem a test2 
imageItem a image 
textItem a text 
blockItem b test3 
imageItem b image 
textItem b text 
imageItem c image 
textItem c text 
imageItem s image 

我的排序功能

array contains type and sortvalue 

array=array.sort(sortFunction); 

function sortFunction(groupA, groupB) { 

    if (groupA.sortValue > groupB.sortValue) { 
     return 1; 
    } else if (groupA.sortValue < groupB.sortValue) { 
     return -1; 
    } 

    return 0; 
} 

它只是排序的文本,但不是那種。我想知道是否有這樣做。非常感謝!

回答

3

使用第二個鍵比較,如果第一個是平等的:

function sortFunction(a, b) { 
    if (a.key1 > b.key1) { 
     return +1; 
    } else if (a.key1 < b.key1) { 
     return -1; 
    } else if (a.key2 > b.key2) { 
     return +1; 
    } else if (a.key2 < b.key2) { 
     return -1; 
    } else 
    ... 
    } else if (a.keyN > b.keyN) { 
     return +1; 
    } else if (a.keyN < b.keyN) { 
     return -1; 
    } else { 
     return 0; 
    } 
} 

或者,爲了更好的可讀性:

function sortFunction(a, b) { 
    if (a.key1 > b.key1) { 
     return +1; 
    } else if (a.key1 < b.key1) { 
     return -1; 
    } 

    if (a.key2 > b.key2) { 
     return +1; 
    } else if (a.key2 < b.key2) { 
     return -1; 
    } 
    ... 

    if (a.keyN > b.keyN) { 
     return +1; 
    } else if (a.keyN < b.keyN) { 
     return -1; 
    } 

    return 0; 
} 
+3

尼斯。順便說一句,你可以縮短它'返回(a.key1> b.key1) - (a.key1 b.key2) - (a.key2 b.keyN) - (a.keyN b.keyN);' – Bergi 2013-02-22 00:04:11

2
if (groupA.type == groupB.type) { 
    /* your code */ 
} 
else if (groupA.type > groupB.type) { 
    return 1; 
} 
else if (groupA.type < groupB.type) { 
    return -1; 
} 

return 0;