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
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
4 Comments
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).myarray[timestamp][1]
1 is the 2nd index in inner array. Indexes start from 0.