2

If I do this:

console.log(result)

In console I get:

[Object, Object, Object, Object, Object]

Where Object expanded looks like:

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

How can I resort result so that the object with letter == # is at the end of the array?

Thanks

2 Answers 2

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

Because '#' is lexicographically before 'a', this sorts by letter reversed, so that your results will come out as "Z, B, A, #". If you want '#' at the end but alphabetics first, perhaps:

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;
  }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but that ends up making the list start at Z, end in #... I want A through Z and then #
@AnApprentice See the edit. (And in the future, young apprentice, learn to fully specify your needs in your question. :)
oh glorious that did working, sure takes a lot of code, man oh man. Thanks for your speedy help.
2

If the letter is lower than A charCode I set it to z char code + 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");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.