...

View Full Version : Sorting arrays with undefined elements (?)



cenze
02-15-2007, 06:50 PM
Hi Everyone,

I've been looking for a way to either ignore or control undefined elements in an array when sorting.

Either I'm overlooking something obvious, or this is really difficult! (most likely the former).

Just a quick picture in case I'm being ambiguous:



//array to be sorted
var array =
[
[A, 1],
[B, 2],
[, 3],
[D, 4],
[E,]
]

//desired outcome when sorting by a[0] b[0] comparison
A 1
B 2
D 4
E
3

//a successful sort on the numbers would leave them unchanged


In other words, I want undefined elements tossed on the bottom (or top depending on viewpoint) of a sort.

Is my terminology correct? Hopefully this makes sense.

Thanks a bunch!
--
Cenze

Arty Effem
02-15-2007, 07:48 PM
Hi Everyone,

I've been looking for a way to either ignore or control undefined elements in an array when sorting.

Just write a comparator function that treats undefined values as you require: LINK (http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:sort)

cenze
02-16-2007, 04:48 PM
Thanks Arty,

Sorry to be a waste of O2...

I did sort of get the results I want by assigning those undefined elements a common value (zero), and just hiding that fact in the display code.

I guess I am not experienced enough to know how to say

if (element == undefined) { assign lowest order rank };

in javascript...
any hints? or a trivial example perhaps?

Much appreciated!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum