2013-01-06 154 views
0

我想按以下方式對值和文本進行排序選擇選項。 文本可以有特殊字符,需要排序。 但是我發現,一些特殊字符是在字母后面出現的。 我首先需要所有特殊字符,然後是字母。Javascript排序陣列

c = [["#test","#test"], ["?test", "?test"], ["test", "test"], ["TEst", "TEst"], ["]test", "]test"]] 
    >>> c.sort() 
    [["#test", "#test"], ["?test", "?test"], ["TEst", "TEst"], ["]test", "]test"], ["test", "test"]] 

該問題似乎是'TEst'。

另一簡單示例:

cool = ['#new','?new','[new',']new','NEw','&new','cool','ind'] 
["#new", "?new", "[new", "]new", "NEw", "&new", "cool", "ind"] 
cool.sort() 
["#new", "&new", "?new", "NEw", "[new", "]new", "cool", "ind"] 

回答

2

問題特別是與ASCII codes 91-96 and 123-126字符,它們是標點或特殊字符,但比字母字符的代碼更高。所以你的排序功能需要考慮到這一點。

例如,您可以通過將這些字符映射到較低的ASCII字符來完成此操作。 http://jsfiddle.net/LGjnY/4/

function transformString(s) { 
    var r = '', 
    code; 
    for (var i = 0; i < s.length; i++) { 
    code = s.charCodeAt(i); 
    // map 91-96 onto 22-27 
    if (code >= 91 && code <= 96) code -= 69; 
    // map 123-126 onto 28-31 
    else if (code >= 123 && code <= 126) code -= 95; 
    r += String.fromCharCode(code); 
    } 
    return r; 
} 
c.sort(function (a, b) { 
    return transformString(a[0]).localeCompare(transformString(b[0])); 
}); 

或組合的比較和改造,使其更快(jsfiddle;沒有真正測試)

function compareTransformedStrings(a, b) { 
    if (a == b) return 0; 
    for (var i = 0, A, B; (A = a.charCodeAt(i)) && (B = b.charCodeAt(i)); i++) { 
     if (A != B) { 
      return A - (A >= 91 && A <= 96) * 69 - (A >= 123 && A <= 126) * 95 
       < B - (B >= 91 && B <= 96) * 69 - (B >= 123 && B <= 126) * 95 
       ? -1 : 1; 
     } 
    } 
    return a.length < b.length ? -1 : 1; 
} 
c.sort(function (a, b) { 
    return compareTransformedStrings(a[0], b[0]); 
}); 
2

可以傳遞一個比較函數作爲.sort()函數參數,像

c.sort(function(a, b) { 
    if (a.charCodeAt(0) <= 49) { 
     return -1; 
    } 

    return a.localeCompare(b); 
}) 

演示:http://jsfiddle.net/7DUEg/

+0

在這個例子中,這並不從默認的排序在所有不同。我猜如果'a'和'b'都低於ASCII 49,那麼排序順序將是不確定的? – Stuart

+0

@Stuart:顯然我給了OP一個*想法*如何改進他的代碼以達到預期的效果。由OP來改變比較功能以適應所有要求。 – zerkms

+0

夠公平的,只是想檢查一下我沒有誤解你的代碼。 – Stuart