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.

share|improve this question
feedback

2 Answers

up vote 3 down vote accepted

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
share|improve this answer
1  
Great job explaining the JavaScript array initialization issue, and proving a good alternative. – Thomas Jones Apr 28 '12 at 12:59
I'm pretty sure most of JS engines in use today can handle sparse arrays pretty good, so there won't be much difference. – Oleg V. Volkov Apr 28 '12 at 14:43
@KooiInc This is superb! I did indeed hit the initialisation issue, and hence why I was struggling. Thanks for the excellent advice. Regards, Ben. – Ben Apr 28 '12 at 16:51
@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). – KooiInc Apr 29 '12 at 7:20
feedback
myarray[timestamp][1]

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

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.