2011-05-02 148 views
2

如果我这样做:如何对数组进行排序?

console.log(result) 

在控制台我得到:

[Object, Object, Object, Object, Object] 

凡对象扩展的样子:

contacts: Array[344] 
letter: "#" 
__proto__: Object 

contacts: Array[11] 
letter: "A" 
__proto__: Object 

contacts: Array[31] 
letter: "B" 
__proto__: Object 

contacts: Array[1] 
letter: "Z" 
__proto__: Object 

我怎么能诉诸结果使之与信对象==#在数组的末尾?

感谢

回答

2
result = result.sort(function(a,b){ 
    a=a.letter; 
    b=b.letter; 
    return a<b?1:a>b?-1:0; 
}); 

因为 '#' 之前按字典 'A',这种种的字母颠倒过来,让你的结果会出来为 “Z,B,A,#”。如果你想在年底,但alphabetics“#”第一个,也许是:

result = result.sort(function(a,b){ 
    a=a.letter; 
    b=b.letter; 
    var aIsLetter = /[a-z]/i.test(a); 
    var bIsLetter = /[a-z]/i.test(b); 
    if (aIsLetter && !bIsLetter){ 
    return -1; 
    }else if (bIsLetter && !aIsLetter){ 
    return 1; 
    } else { 
    return a<b?-1:a>b?1:0; 
    } 
}); 
+0

谢谢,但该结束使列表从Z开始,结束于#...我想要A到Z然后# – AnApprentice 2011-05-02 02:38:06

+2

@AnApprentice请参阅编辑。 (而且在未来,年轻的学徒,学会在你的问题中充分说明你的需求。:) – Phrogz 2011-05-02 02:41:44

+0

噢光荣,确实工作,肯定需要很多代码,男人哦。感谢您的快速帮助。 – AnApprentice 2011-05-02 02:45:12

2

如果信件低于A则charCode我将它设置为z字符代码+ 1,see this example on jsFiddle

var list = [{contacts: [], letter: "#", __proto__: {}}, 
      {contacts: [], letter: "A", __proto__: {}}, 
      {contacts: [], letter: "Z", __proto__: {}}, 
      {contacts: [], letter: "B", __proto__: {}}]; 


list.sort(function(a, b){ 
    a = a.letter.charCodeAt(0); 
    b = b.letter.charCodeAt(0); 

    if (a < 65) a = "z".charCodeAt(0) + 1; 
    if (b < 65) b = "z".charCodeAt(0) + 1; 

    return a>b; 
}); 

$(list).each(function(){  
    $("<span />").html(this.letter).appendTo("pre"); 
});