Javascript - create array index and access

13,878

Solution 1

If you use an array that way, you'll end up with an array containing a large amount of undefined values:

var myarr = [];
myarr[1000] = 'hello';
console.log(myarr.length); //=> 1001 
console.log(myarr[0]); //=> undefined
console.log(myarr[999]); //=> undefined

So, you may want to use an object for that and use some kind of sorting. For example

var myobj = {}, timestamp = new Date().getTime();
myobj[timestamp] =   ['hello','world'];
myobj[timestamp+1] = 'how are we today?';

function retrieveSorted(obj){
  var keys = Object.keys(obj).sort(), key, ret = [];
  while(key = keys.shift()){
    ret.push(obj[key]);
  }
  return ret;
}

var sorted = retrieveSorted(myobj); 
   //=> [["hello", "world"], "how are we today?"]
myobj[timestamp][1]; //=> world

Solution 2

myarray[timestamp][1]

1 is the 2nd index in inner array. Indexes start from 0.

Share:
13,878
Ben
Author by

Ben

Updated on November 22, 2022

Comments

  • Ben
    Ben over 1 year

    I am looking to create a simple array using a time stamp for the index so that I can access the values by timestamp without iterating through the array, however I am struggling!

    I need to be able to set 2 values for each row.

    For example:

    var myarray = [];
    var test1 = 'hello'
    var test2 = 'world'
    
    myarray[timestamp] = [test1, test2];
    

    So for a given timestamp e.g. 12345678, how could I access the value of test2?

    Appreciate any thoughts and advice.

    Regards, Ben.

  • Thomas Jones
    Thomas Jones almost 12 years
    Great job explaining the JavaScript array initialization issue, and proving a good alternative.
  • Oleg V. Volkov
    Oleg V. Volkov almost 12 years
    I'm pretty sure most of JS engines in use today can handle sparse arrays pretty good, so there won't be much difference.
  • Ben
    Ben almost 12 years
    @KooiInc This is superb! I did indeed hit the initialisation issue, and hence why I was struggling. Thanks for the excellent advice. Regards, Ben.
  • KooiInc
    KooiInc almost 12 years
    @Oleg: the maximum array length is 4294967295. If you use a timestamp index (which may be much larger than that maximum), the length of that array will actually be 0, and Array methods render more or less unusable (will not throw an error, but just won't return a value or not do what you expect them to do).
  • KevinIsNowOnline
    KevinIsNowOnline almost 11 years
    In my experience, in yourArray[i][prop], the i is the counter that lets you access the object's property values. Cheers!