0

Probably, I have a stupid question, but how can I sort alphanumeric text in select's option? Example:

  <select> <option>H123-128kbps</option>
           <option>H123-1024kbps</option>
           <option>H130-128kbps</option>
           <option>H123-512kbps</option>
           <option>H123-256kbps</option>
           <option>H130-256kbps</option>
  </select>

I would like to sort it like:

      <select><option>H123-128kbps</option>
              <option>H123-256kbps</option>
              <option>H123-512kbps</option>
              <option>H123-1024kbps</option>
              <option>H130-128kbps</option>                  
             <option>H130-256kbps</option>
        </select>

Currently, I receive partial results:

      <select><option>H123-128kbps</option>
              <option>H123-512kbps</option>
              <option>H123-1024kbps</option>
              <option>H123-256kbps</option>                  
              <option>H123-1024kbps</option>
              <option>H130-256kbps</option>
              <option>H130-128kbps</option>                
        </select>

This is my code :

            var options = $('select.whatever option'); 
            var arr = options.map(function (_, o) {
                return {t: $(o).text(), v: o.value};
            }).get();
            arr.sort(function (o1, o2) {
                return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
            });
            options.each(function (i, o) {
                o.value = arr[i].v;
                $(o).text(arr[i].t);
            });

Thanks a lot in advance :)

Evgeny
  • 193
  • 2
  • 13
  • I tried to sort in a lot of different ways, like var arr = options.map(function (_, o) { return {t: $(o).text(), v: o.value}; }).get(); arr.sort(function (o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; }); options.each(function (i, o) { o.value = arr[i].v; $(o).text(arr[i].t); }); but it's sort by the first part of my string: H123 and fully ignore the second part after "-" – Evgeny May 31 '18 at 14:37
  • I think you need to split the string compare the first and second (if the first part is the same) – Eddie May 31 '18 at 14:42
  • And why do you have `td` on your js when you dont have `td` on your html? – Eddie May 31 '18 at 14:47
  • I have it. Just don't want to post all html code here. – Evgeny May 31 '18 at 14:50
  • Edited my previous code – Evgeny May 31 '18 at 14:53

0 Answers0