Results 1 to 3 of 3

Thread: How do I sort an array of Strings, ignoring "THE", "A", and "AN" from the beginning?

  1. #1
    Join Date
    Sep 2005

    Question How do I sort an array of Strings, ignoring "THE", "A", and "AN" from the beginning?

    Basically I want to sort an array of Strings like iTunes sorts its titles. This means ignoring certain words that are at the beginning of the title.

    Here's what I have so far, and it seems to sorta work, but not properly, and not at all properly in IE. And btw, I'm using Prototype, so that explains the .startsWith function:

    var ignoreWords = ["A", "AN", "THE"];
    function sortTitles(a, b) {
        for (var i = 0; i < ignoreWords.length; i++) {
            if (a.toUpperCase().startsWith(ignoreWords[i] + " ")) {
                a = a.substr(ignoreWords[i].length);
            if (b.toUpperCase().startsWith(ignoreWords[i] + " ")) {
                b = b.substr(ignoreWords[i].length);
        return a > b;
    So, given an array of strings, some of them being like "The Wall", so that they are sorted differently, the function above doesn't work properly. Any ideas?

  2. #2
    Join Date
    Feb 2006
    function sortTitles(a, b){
        var rx= /^ *(a|an|the)\b */;
        a= a.toLowerCase().replace(rx,'');
        b= b.toLowerCase().replace(rx,'');
        if(a== b) return 0;
        return a> b? 1: -1;
    var A= ['The Slow Dog', 'The Fat Cat','An Army of One',
    'An Angry Dog','A Car Chase'];


  3. #3
    Join Date
    Sep 2005
    mrhoo, that works PERFECTLY! Thanks a million! I'll credit you in the comments for the function

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center