2

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'
   }
]

2 Answers2

5

Your dates are in a format that will sort lexicographically, which means you don't need to spend the resources creating new Date objects just to find the largest. You also don't need to sort the list, you can find the most recent in a single pass with a loop or reduce() which is more efficient:

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'}]

let most_recent = files.reduce((mostRecent, item) =>
   item.created_at > mostRecent.created_at 
   ? item
   : mostRecent
)
console.log(most_recent)
Mark
  • 90,562
  • 7
  • 108
  • 148
1

Do this:

files.sort(function(a,b){
    return new Date(b.created_at) - new Date(a.created_at);
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79