Reputation: 1601
I have two variables in my javascript.
A message function : var message
A timestamp function : var date
(It is of type timestamp)..
Now I have an array which stores messages according to there timestamp. Something like
var input = []; //dynamic array to store both message and date
var date = new Date(update.data.history[i].timestamp * 1000); //Getting from Json object
var date_input = date.toLocaleTimeString();
var message = update.data.history[i].message;
for (i to length)
{
input.push({ key: date_input, value: message }); //Key refers to date, and value to message
}
input.sort(sort_by(key,true,parseInt));
My function sort_by
var sort_by = function(field, reverse, primer){
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return (A < B ? -1 : (A > B ? 1 : 0)) * [1, -1][+!!reverse];
}
}
Now, I tried debugging with firebug and noticed my sorting function is not working. I am using timestamp as key but still no luck. Is there anyway I can sort it according to timestamp and then display it. I tried other sorting solutions on SO, but I guess there is another way to sort when there is datatype like timestamp?
Upvotes: 1
Views: 1415
Reputation: 1601
The sorting function works perfectly. When I was debugging it with firebug, I saw on the console that even though date-input was "6-29-07 am", it was only taking 6 as the "key", therefore every entry on that particular day was assigned the same key. Therefore, sorting was not able to give the desired output. Therefore, I avoided new date() function in second line, directly took the timestamp as key, sorted accordingly, and then convert it into date-format. Silly error, but took some time.
Upvotes: 1
Reputation: 105885
In an object literal, you do not have to quote the key:
input.push({ key: date_input, value: message });
However, your function takes three arguments, which aren't given in an object-like notation, so the meaning of key
is unknown and will result in a ReferenceError:
input.sort(sort_by(key,true,parseInt)); ^ ReferenceError: key is not defined
Use a string as argument instead and it should work:
input.sort(sort_by("key",true,parseInt));
Upvotes: 1