Sorry I am new to javascript, but I am currently attempting to sort my JSON object according to attribute but right now it does not sort.
For example: I try to do this:
function sortByKey(array, key)
{
return array.sort(function(a, b) {
let x = a[key];
let y = b[key];
x = new Date(a.dateModified);
y = new Date(b.dateModified);
return x>y ? -1 : x<y ? 1 : 0;
});
}
And I try to sort according to "lastCompletedEvaldate" :
[
{
"_id": "<a MongoDB object ID>",
"name": "Fred Flintstone",
"email": "fflintstone@hotmail.com",
"sex": "male",
"tags": [
"foo",
"bar"
],
"lastCompletedEvalDate": "2018-05-14 12:02:14.955",
"pendingEvalSentDate": null,
"pendingEvalViewedEmailDate": null,
"pendingEvalClickedLinkDate": null
},
{
"_id": "<a MongoDB object ID>",
"name": "Barney Rubble",
"email": "barney@gmail.com",
"sex": "intersex",
"tags": [],
"lastCompletedEvalDate": "2018-05-14 12:02:14.954",
"pendingEvalSentDate": "2018-05-14 12:02:14.955",
"pendingEvalViewedEmailDate": "2018-05-14 12:02:14.955",
"pendingEvalClickedLinkDate": "2018-05-14 12:02:14.955"
},
{
"_id": "<a MongoDB object ID>",
"name": "Bambam Rubble",
"email": "bam@bam.com",
"sex": null,
"tags": [
"baz"
],
"lastCompletedEvalDate": "2018-05-14 12:02:14.955",
"pendingEvalSentDate": null,
"pendingEvalViewedEmailDate": null,
"pendingEvalClickedLinkDate": null
}
]
However, when I use the function like so:
let temp = sortByKey(file, 'lastCompletedEvalDate');
and output it using a get request:
router.get('/dash/participant', function(req, res){
res.send(temp);
});
I still get the same output back not sorted. Am I doing something wrong.