Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  3] [ 6]  / answers: 1 / hits: 16471  / 12 Years ago, sat, april 28, 2012, 12:00:00

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.


More From » arrays

 Answers
64

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

[#85912] Thursday, April 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristinadomoniquel

Total Points: 320
Total Questions: 94
Total Answers: 94

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
cristinadomoniquel questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Mon, Aug 17, 20, 00:00, 4 Years ago
;