Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Oct 2006
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Sorting arrays with undefined elements (?)

    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:

    Code:
    //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

  • #2
    Banned
    Join Date
    May 2006
    Location
    England
    Posts
    664
    Thanks
    0
    Thanked 84 Times in 84 Posts
    Quote Originally Posted by cenze View Post
    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

  • #3
    New to the CF scene
    Join Date
    Oct 2006
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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!


  •  

    Posting Permissions

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