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?
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?
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);
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)
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.