I have a problem getting the second highest date in ES6. I’m using moment.js
too.
Its supposed to be getting the id
of 3.
JavaScript
x
24
24
1
const datas = [
2
{
3
id: 1,
4
date: moment(String('Apple & Banana - 20072021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
5
},
6
{
7
id: 2,
8
date: moment(String('Apple & Oranges - 30082021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
9
},
10
{
11
id: 3,
12
date: moment(String('Lemon & Oranges - 30102021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
13
},
14
{
15
id: 4,
16
date: moment(String('Honeydew - 30112021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
17
}
18
];
19
20
const secondLatestDate = new Date(datas.map(file => new Date(file.date)).sort().reverse()[1]);
21
22
const finalResult = datas.find(file => file.date.getTime() === secondLatestDate.getTime());
23
24
console.log(finalResult)
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Advertisement
Answer
You should use custom sort function as:
JavaScript
1
2
1
datas.sort((a, b) => a.date - b.date)
2
There is no need to use find
when you are reverse
ing the array and getting the index 1
from it.
Note: I deliberately change the order of the datas array
JavaScript
1
20
20
1
const datas = [{
2
id: 1,
3
date: moment(String('Apple & Banana - 20072021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
4
},
5
{
6
id: 2,
7
date: moment(String('Apple & Oranges - 30082021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
8
},
9
{
10
id: 4,
11
date: moment(String('Honeydew - 30112021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
12
},
13
{
14
id: 3,
15
date: moment(String('Lemon & Oranges - 30102021').match(/[0-9]/g).join(""), 'DDMMYYYY').toDate()
16
}
17
];
18
19
const secondLatestDate = datas.sort((a, b) => a.date - b.date).reverse()[1];
20
console.log(secondLatestDate);
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
or you can directly find the second largest after sort. There is no need to reverse
the array
JavaScript
1
2
1
datas.sort((a, b) => a.date - b.date)[datas.length - 2]
2
JavaScript
1
32
32
1
const datas = [{
2
id: 1,
3
date: moment(
4
String('Apple & Banana - 20072021').match(/[0-9]/g).join(''),
5
'DDMMYYYY'
6
).toDate(),
7
},
8
{
9
id: 2,
10
date: moment(
11
String('Apple & Oranges - 30082021').match(/[0-9]/g).join(''),
12
'DDMMYYYY'
13
).toDate(),
14
},
15
{
16
id: 4,
17
date: moment(
18
String('Honeydew - 30112021').match(/[0-9]/g).join(''),
19
'DDMMYYYY'
20
).toDate(),
21
},
22
{
23
id: 3,
24
date: moment(
25
String('Lemon & Oranges - 30102021').match(/[0-9]/g).join(''),
26
'DDMMYYYY'
27
).toDate(),
28
},
29
];
30
31
const secondLatestDate = datas.sort((a, b) => a.date - b.date)[datas.length - 2];
32
console.log(secondLatestDate);
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>