Eugene Goldberg Eugene Goldberg - 6 months ago 42
Javascript Question

how to calculate max date of a date field of an object?

In my node.js app I have the following array of objects, which includes a date field named REPORTEDDATE:

[ { INCIDENTNUMBER: 'INC000000000002',
SUBMITTER: 'Chris',
REPORTEDDATE: Mon May 09 2016 18:17:04 GMT+0000 (UTC),
LASTRESOLVEDDATE: Mon May 09 2016 18:17:04 GMT+0000 (UTC),
OWNERGROUP: 'ACME Help Desk',
COMPANY: 'ACME Inc',
CATEGORIZATIONTIER1: 'cat-1',
CATEGORIZATIONTIER2: 'cat-2',
CATEGORIZATIONTIER3: 'cat-3',
RESOLUTIONCATEGORY: 'res-cat',
RESOLUTIONCATEGORYTIER2: 'res-cat-2',
RESOLUTIONCATEGORYTIER3: 'res-cat-3',
REPORTEDSOURCE: 'Phone',
DESCRIPTION: 'Some description',
ID: 9 },
{ INCIDENTNUMBER: 'INC000000000002',
SUBMITTER: 'Chris',
REPORTEDDATE: Mon May 09 2016 18:17:09 GMT+0000 (UTC),
LASTRESOLVEDDATE: Mon May 09 2016 18:17:09 GMT+0000 (UTC),
OWNERGROUP: 'ACME Help Desk',
COMPANY: 'ACME Inc',
CATEGORIZATIONTIER1: 'cat-1',
CATEGORIZATIONTIER2: 'cat-2',
CATEGORIZATIONTIER3: 'cat-3',
RESOLUTIONCATEGORY: 'res-cat',
RESOLUTIONCATEGORYTIER2: 'res-cat-2',
RESOLUTIONCATEGORYTIER3: 'res-cat-3',
REPORTEDSOURCE: 'Phone',
DESCRIPTION: 'Some description',
ID: 10 } ]


Is there a way to determine the max date across the REPORTEDDATE fields of these objects?
I know - the better way of asking would be to describe what I have tried, but, with this format, I don't really know where to begin...

Answer

You can do it quite simply with map, reduce, Math.max, and Date.parse().

var maxDate = new Date(objectArray.map(o => o.REPORTEDDATE).reduce(function(a, b) {
    return Math.max(a, Date.parse(b));
}, 0));