I am facing a challenge with sorting a list of JSON objects based on a unix timestamp field within each object. To tackle this issue, I created a sorting function
function sortUnixTimestamp(a, b){
var a = parseInt(a.timestamp);
var b = parseInt(b.timestamp);
return ((a > b) ? -1 : ((a < b) ? 1 : 0));
}
Despite objects not being arrays, I attempted to use
[].sort.call(object).sort(sortUnixTimestamp);
. However, sporadically, I encounter the error message [].sort.call(...).sort is not a function
Another approach I tried was to treat it like an array by applying
(object).sort(sortUnixTimestamp);
, yet again, intermittently encountering the error message (...).sort is not a function
This inconsistency in functionality puzzles me. Why does it work sometimes but fail at other times? How can I overcome this stumbling block?
Additional Detail: The structure of each object is as follows:
{
"field1": "string",
"field2": "string",
"timestamp": 0
}
Hence, the list comprises entries like
[
{
"field1": "string",
"field2": "string",
"timestamp": 0
},
{
"field1": "string",
"field2": "string",
"timestamp": 0
},
...
]