Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Sorting Select.options[] array on text or value attribute

212 views
Skip to first unread message

Clyde Ingram

unread,
Jun 11, 2002, 5:17:04 AM6/11/02
to
Here is a simple problem with sorting an array of Options in a Select
field, by their "text" (or "value") attributes.

(My browsers are Netscape 4.6 and IE 5.)

I have a "Select" object called "myselection".
On the browser, this shows a pick-list sorted alphabetically by the
"text" attribute of each "Option" in the "Select" object. For example:

AAA
BBB
CCC
DDD
EEE

When the user enters some text (for example "ABC") and presses an "Add"
Button, the text is validated, and then added to the "Select" pick-list.

The new text string appears at the end of the pick-list, because that is
where my Javascript adds it. For example:

AAA
BBB
CCC
DDD
EEE
ABC

I then try to sort the resulting "Select" pick-list alphabetically by
"text" attribute of each Option object in the "options[]" array, but
this has no effect on the sort order of the pick-list - the new text
string remains at the end of the list, out of alphabetical order.

(Changing to sort on "value" attribute instead of "text" does not help.)

I would like to sort the options so that they are shown in order like:

AAA
ABC
BBB
CCC
DDD
EEE

Here is the code snippet I use for sorting:

document.myform.myselection.options.sort( sort_by_option_text );

. . .

function sort_by_option_text( a, b ) {

if ( a.text > b.text ) { return 1; } else
if ( a.text < b.text ) { return -1; } else
{ return 0; }
}

Note that I call the "sort()" method of the "options[]" array.
I pass it one parameter - the name of a sorting function
"sort_by_option_text" that I define later.

The function definition follows the style of the O'Reilly "JavaScript"
book (David Flanagan's "The Definitive Guide") by declaring 2 parameters
"a" and "b", which I understand are implicitly elements of the
"options[]" array (Option objects).

Since I want to sort on the "text" attribute of each pair of Option
objects in the "options[]" array, I do an alphabetic comparison of the
"text" attribute of such pairs of Objects. For example:

if ( a.text > b.text )

And, in accordance with the book, the sort function returns:

- a positive number, if option "a" comes after option "b"
- a negative number, if option "a" comes before option "b"

- zero, if options "a" and "b" are identical.

Thank-you in advance for suggestions on how to make this work.

Regards,
Clyde Ingram.

Clyde Ingram

unread,
Jun 11, 2002, 5:52:08 AM6/11/02
to
In message <af3CEMBQ...@pjocs.demon.co.uk>, Clyde Ingram
<cin...@pjocs.demon.co.uk> writes

>Here is a simple problem with sorting an array of Options in a Select
>field, by their "text" (or "value") attributes.
>

A quick glance at deja.com throws up an old solution (1998) from Steve
van Dongen. I am surprised that the problem he discusses - that the
"options[]" array does not have a "sort()" method, has not been fixed
long ago. Can anyone comment on this please?

Steve's solution is to copy the "options[]" array to a new local Array
object, sort it, then copy the newly sorted Array back over the original
"options[]" array.

Ta,
Clyde

P.S. Here is the dialog from comp.lang.javascript:

My first time sorting a list too. :) The sortOptions(list) function is
pretty self-expanitory I think but I suspect you'll be wondering about
compareOptionText(a,b). The sort function has an optional parameter
that you can use to specify your own comparison function to be used by
sort(). In this case, the array held Option objects which have to be
sorted by their text property, so that's what compareOptionText does.
Parameters a and b are passed to it by sort and the expected return
values are listed there in comments.

Works in NN3+ & IE4 at least.

Cheers,
Steve

function compareOptionText(a,b) {
/*
* return >0 if a>b
* 0 if a=b
* <0 if a<b
*/
// textual comparison
return a.text!=b.text ? a.text<b.text ? -1 : 1 : 0;
// numerical comparison
// return a.text - b.text;
}

function sortOptions(list) {
var items = list.options.length;
// create array and make copies of options in list
var tmpArray = new Array(items);
for ( i=0; i<items; i++ )
tmpArray[i] = new
Option(list.options[i].text,list.options[i].value);
// sort options using given function
tmpArray.sort(compareOptionText);
// make copies of sorted options back to list
for ( i=0; i<items; i++ )
list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
}

<SELECT NAME="list" SIZE=1
OnChange="alert('value='+this.options[this.selectedIndex].value)">
<OPTION VALUE="value1">1
<OPTION VALUE="value3">3
<OPTION VALUE="value2">2
<OPTION VALUE="value10">10
<OPTION VALUE="value8">8
<OPTION VALUE="value4">4
<OPTION VALUE="value6">6
<OPTION VALUE="value5">5
<OPTION VALUE="value7">7
<OPTION VALUE="value9">9
</SELECT>
<INPUT TYPE="BUTTON" NAME="sort" VALUE=" Sort "
OnClick="sortOptions(this.form.list)">


"A.H." wrote:
>
> I would like to make a function that will be able to sort those items.
Do
> you have any suggestions as to how to go about it? This would be the
first
> time I've ever tried anything like this, and I've never seen any
examples
> anywhere to learn from.
>
> Thank you,
> A.H.
>
> Steve van Dongen wrote in message <366D9F62...@uniserve.com>...
> >
> >While it's true to say that options are viewed as arrays of select
> >objects, it isn't true to say that options *are* arrays. Options are
> >accessed like arrays but in fact they are objects, and therefore, do
not
> >have a sort method. The way I see it, you have two options -- #1 is
to
> >write a function to copy the options into a real array and call its'
> >sort method and then copy the options back, or #2, write your own
sort
> >method to sort the options directly.
> >
> >Regards,
> >Steve


brotherli

unread,
Jun 11, 2002, 8:37:07 AM6/11/02
to

Clyde Ingram wrote:

> In message <af3CEMBQ...@pjocs.demon.co.uk>, Clyde Ingram
> <cin...@pjocs.demon.co.uk> writes
>
>>Here is a simple problem with sorting an array of Options in a Select
>>field, by their "text" (or "value") attributes.
>
> A quick glance at deja.com throws up an old solution (1998) from Steve
> van Dongen. I am surprised that the problem he discusses - that the
> "options[]" array does not have a "sort()" method, has not been fixed
> long ago. Can anyone comment on this please?


There's no need to 'fix' that because the options array is not a
"normal" array as we define it with new Array(); It's an array of
objects and giving a sort() function to it would be rather difficult
because the sorting criterias are not clear. BTW: you can't sort
associative or multi-dimension arrays because of that reason.


>
> Steve's solution is to copy the "options[]" array to a new local Array
> object, sort it, then copy the newly sorted Array back over the original
> "options[]" array.


That's what I'd suggest too.


>
> Ta,
> Clyde
>


--

brotherli

[ mails to nu...@brotherli.ch won't be read! replace it with master. ]

Martin Honnen

unread,
Jun 11, 2002, 9:17:44 AM6/11/02
to
Clyde Ingram wrote:
> In message <af3CEMBQ...@pjocs.demon.co.uk>, Clyde Ingram
> <cin...@pjocs.demon.co.uk> writes
>
>>Here is a simple problem with sorting an array of Options in a Select
>>field, by their "text" (or "value") attributes.
>>
>
>
> A quick glance at deja.com throws up an old solution (1998) from Steve
> van Dongen. I am surprised that the problem he discusses - that the
> "options[]" array does not have a "sort()" method, has not been fixed
> long ago. Can anyone comment on this please?

The sort method is defined for core language arrays, don't expect DOM
arrays to have that method (what should happen with
document.images.sort??). And NN4 hasn't changed anyway since 1998

--

Martin Honnen
http://javascript.faqts.com/
http://home.t-online.de/home/martin.honnen/jsgoddies.html

GalaSoft Laurent Bugnion

unread,
Jun 11, 2002, 4:05:55 PM6/11/02
to
Hi,

I must correct you in that options[] is a normal array, and is even
indexed (not associative). You can see that by doing:

var mySelect = document.formName.selectName;

for ( var index = 0; index < mySelect.options.length; index++ )
{
alert( mySelect.options[ index ].text );
}

for example. Besides, you can easily sort arrays of objects by providing
a sorting function to the sort() method. This is explained in the
documentation at
http://developer.netscape.com/docs/manuals/js/client/jsref/array.htm#1196882

You are right that associative arrays cannot be sorted.

The reason why it cannot be sorted is rather that it's an array given by
the DOM, as Martin is explaining in his post.

Laurent
--
GalaSoft Laurent Bugnion
Webdesign, Java, JavaScript: http://www.galasoft-LB.ch
Visit Malaysia: http://mypage.bluewin.ch/lbugnion/malaysia/introve.htm
Support children in Calcutta: http://www.calcutta-espoir.ch

0 new messages