How to find the most recent date in an array with key values in Javascript

1256 views javascript
3

In this array of files, I have to find which file was created the most recently. Do I have to change the format of the date or can function work with it as it is?

let  files = [
  {
    name: 'untitled',
     created_at: '2015-02-03T09:43:03Z'
   },
  {
    name: 'ruby files',
     created_at: '2014-04-16T22:13:29Z'
   },
  {
    name: 'documents',
     created_at: '2016-05-09T09:39:24Z'
   }
]

answered question

2 Answers

5

Do this:

files.sort(function(a,b){
    return new Date(b.created_at) - new Date(a.created_at);
});

posted this
1

That string follows what specification states -> Read more here

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ.

You can parse or instantiate a new object Date using that string as follow

new Date('2016-05-09T09:39:24Z') // New object Date
Date.parse('2016-05-09T09:39:24Z') // returns the number of milliseconds since January 1, 1970, 00:00:00 UTC

This is an approach to get the most recent file

let  files = [  {    name: 'untitled',     created_at: '2015-02-03T09:43:03Z'   },  {    name: 'ruby files',     created_at: '2014-04-16T22:13:29Z'   },  {    name: 'documents',     created_at: '2016-05-09T09:39:24Z'   }],
     // The slice is to avoid mutation in original array.
     mostRecent = files.slice().sort((a, b) => new Date(a.created_at) - new Date(b.created_at)).pop();

console.log(mostRecent);
.as-console-wrapper { max-height: 100% !important; top: 0; }

posted this

Have an answer?

JD

Please login first before posting an answer.