1

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.

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

4 Comments

Great job explaining the JavaScript array initialization issue, and proving a good alternative.
I'm pretty sure most of JS engines in use today can handle sparse arrays pretty good, so there won't be much difference.
@KooiInc This is superb! I did indeed hit the initialisation issue, and hence why I was struggling. Thanks for the excellent advice. Regards, Ben.
@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).
2
myarray[timestamp][1]

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

1 Comment

In my experience, in yourArray[i][prop], the i is the counter that lets you access the object's property values. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.