如何排序数组?

时间:2011-05-02 02:35:01

标签: javascript arrays

如果我这样做:

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 个答案:

答案 0 :(得分: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,#”。如果你想要最后的'#',但首先是字母,或许:

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;
  }
});

答案 1 :(得分: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");
});