Web Analytics Made Easy -
StatCounter RegExp sorting - CodingForum

Announcement

Collapse
No announcement yet.

RegExp sorting

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • RegExp sorting

    I am not (yet ) very good on RegExp, so can anyone help me sorting an array using RegExp?

    a = new Array()
    a[0] = 'b';
    a[1] = '1';
    a[2] = 'a';
    a[3] = '2';

    I need to change the order in array so, after the sorting, I'd like to have the array in normal sorting (number-alphabetical)

    a[0] = '1';
    a[1] = '2';
    a[2] = 'a';
    a[3] = 'b';
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #2
    Hmm, I'm not sure I understood, but why do u need RegExp?
    Code:
    compare=function(a,b){
        if(a<b)return -1;
        if(a>b)return 1;
        return 0;
    }
    
    a = new Array() 
    a[0] = 'b'; 
    a[1] = '1'; 
    a[2] = 'a'; 
    a[3] = '2'; 
    
    a.sort(compare);
    
    alert(a.join("\n"));
    /Daniel

    Comment


    • #3
      That's a bit overkill - the sort function by default sorts lexically, alphanumerically, case grouping. The only thing you need to do is to run the sort method of the array object in question. See:

      ['b','ab','aa',2,10,1,'a','A'].sort(); => [1,10,2,'A','a','aa','ab','b']
      liorean <[[email protected]]>
      Articles: RegEx evolt wsabstract , Named Arguments
      Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
      Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

      Comment


      • #4
        David is of couse completely correct; answered here as well: http://forums.webdeveloper.com/showt...threadid=28702.
        Last edited by fredmv; Feb 25, 2004, 10:21 PM.
        Moderator @ WebDeveloper.com
        Mentor @ WebXpertz.net

        Comment


        • #5
          But if you want it to be case-insensitive...
          Code:
          function compare(a,b){
              a=a.toLowerCase();
              b=b.toLowerCase();
              if(a<b) return -1;
              if(a>b) return 1;
              return 0;
          }
          or if you're comparing date strings...
          Code:
          function compare(a,b) {
            if (Date.parse(a) < Date.parse(b)) return -1;
            if (Date.parse(a) > Date.parse(b)) return 1;
            return 0;
          }
          Glenn
          vBulletin Mods That Rock!

          Comment


          • #6
            Thank you all.

            Actually I might need either RegExp or split() before sorting, as I have long strings, 2 or 3 words (name, surname) and intend to sort them by first, second or third word in string.

            Anyway, this is the kind of work I can do it by myself. I just never use the sort() method before.
            KOR
            Offshore programming
            -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

            Comment

            Working...
            X