3
var myArray = [
{id:1, date: '2019-01-01'},
{id:2, date: '2018-01-01'},
{id:1, date: '2017-01-01'},
]

I have an array of objects, each object with a date.

What is an elegant way to find the object that contains the latest date?

Charles
  • 41
  • 1
  • 6
  • 1
    Does this answer your question? [What is the elegant way to get the latest date from array of objects in client side?](https://stackoverflow.com/questions/36577205/what-is-the-elegant-way-to-get-the-latest-date-from-array-of-objects-in-client-s) – Niels Bosman Feb 13 '20 at 14:40
  • @NielsBosman It doesn't that will return just the latest date. I need to somehow get the object that contains the date – Charles Feb 13 '20 at 14:41
  • 1
    Please show us any non-elegant code that you have tried. – rahul tyagi Feb 13 '20 at 14:42
  • 2
    is the array sorted? what if more objects have the same date? – Nina Scholz Feb 13 '20 at 14:45

3 Answers3

5

You could reduce the array and pick the latest date with a single loop approach.

var array = [{ id: 1, date: '2019-01-01' }, { id: 2, date: '2018-01-01' }, { id: 1, date: '2017-01-01' }],
    result = array.reduce((a, b) => a.date > b.date ? a : b);

console.log(result);

Another approach by collecting all objects with the latest date.

var array = [{ id:1, date: '2019-01-01' }, { id:2, date: '2018-01-01' }, { id:1, date: '2017-01-01' }],
    result = array.reduce((r, o) => {
        if (!r || r[0].date < o.date) return [o];
        if (r[0].date === o.date) r.push(o);
        return r;
    }, undefined);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use .sort() and passing your compare function, in this instance we are using b - a so you would sort the array from big to small date and take the first entry with .shift().

Example:

const data = [{
    id: 1,
    date: '2016-02-01'
  },
  {
    id: 1,
    date: '2019-01-01'
  },
  {
    id: 2,
    date: '2018-01-01'
  },
  {
    id: 1,
    date: '2017-01-01'
  },
  {
    id: 1,
    date: '2018-02-02'
  },
]

const latest = data.sort((a ,b) => new Date(b.date).getTime() - new Date(a.date).getTime()).shift()

console.log(latest)
GibboK
  • 71,848
  • 143
  • 435
  • 658
0

Just get the first element by index:

myArray.sort((a, b)=> new Date(b.date) - new Date(a.date))[0];

An example:

var myArray = [
    {id:1, date: '2019-01-01'},
    {id:2, date: '2018-01-01'},
    {id:1, date: '2017-01-01'},
    ];

const result = myArray.sort((a, b)=> new Date(b.date) - new Date(a.date));
console.log(result[0]);
console.log(result.shift());

Maybe by using shift() method of sorted array. However:

myArray.sort((a, b)=> new Date(b.date) - new Date(a.date)).shift()

However, be careful shift removes the first element from an array and returns that removed element. This method changes the length of the array.

StepUp
  • 36,391
  • 15
  • 88
  • 148