Advanced Search

Results 1 to 3 of 3

Thread: How to get first/last elements of an associative array?

  1. #1
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default How to get first/last elements of an associative array?

    Hi all,

    How do you find the first and last elements of an associative array?

    Seems simple, but it escapes me.

    Thanks!

  2. #2
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default

    Define "first" and "last".

    You could try using a for-in loop:
    Code:
    for(var x in obj) {
      if(obj.hasOwnProperty(x))
        alert(x + ":" + obj[x]);
    }
    Trinithis

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,694
    Thanks
    43
    Thanked 3,132 Times in 3,096 Posts
    Blog Entries
    12

    Default

    There are no elements in a javascript associative array.

    Code:
    var assocArray = new Array();
    assocArray['bob'] = null;
    assocArray['joe'] = 2000;
    assocArray['albrecht'] = 'E = Mc squared';
    
    // show 'first' value stored
    ;(function(){
     for (var p in assocArray) 
     if(assocArray.hasOwnProperty(p)){
      alert("'first\' key: " + p + ", value's: " + assocArray[p]);
      break;
    };
    })();
    
    // show 'last' value stored
    ;(function(){
     var pv;
     for (var p in assocArray) 
     if(assocArray.hasOwnProperty(p))
      pv = "'last' key: " + p + ", value's: " + assocArray[p];
     alert(pv);
    })();
    Notes: Often javascript Objects are thought of as associative arrays. They would act the same in the above code. They are structured as associative arrays. However, I chose to use an actual array to illustrate a point. The above array has a length of 0, so technically has no first or last (or any) elements. It has properties. Javascript Arrays are also javascript Objects, but javascript Objects are not necessarily (strictly speaking are never) javascript Arrays. If created with the Object constructor, they have no intrinsic length property (undefined).
    Last edited by jscheuer1; 10-25-2008 at 09:55 AM. Reason: add dramatic opening line
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

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