0

Dates string array is constructed from backend data object as below:

const dates: string[] = this.data.map((item:any) => item.date.jsdate);

The result is

dates = [
    Thu Jan 12 2015 00:00:00 GMT+0530 (India Time), 
    Tue Feb 25 2015 00:00:00 GMT+0530 (India Time), 
    Sun Jan 28 2016 00:00:00 GMT+0530 (India Time)
]

typeof(dates) is "object"

How to find the get the latest date among the jsdates array?

Is it possible to apply max function of date-fns?

1

2 Answers 2

2

Convert each to a Date object and compare using getTime() function.

var dates = [
    'Thu Jan 12 2015 00:00:00 GMT+0530 (India Time)', 
    'Tue Feb 25 2015 00:00:00 GMT+0530 (India Time)', 
    'Sun Jan 28 2016 00:00:00 GMT+0530 (India Time)'
]

console.log(
  dates.sort((a,b)=>new Date(b).getTime() - new Date(a).getTime())[0]
)

Sign up to request clarification or add additional context in comments.

Comments

1

I can offer one solution, using the momentjs (https://momentjs.com/) library.

You can sort the dates using:

dates = dates.sort((a,b) => moment(a).diff(moment(b));

Then if you want the latest date you could take the last element from that array:

return dates[dates.length-1];

You should also be able to do this without moment:

dates = dates.sort((a,b) => new Date(b) - new Date(a));

3 Comments

useful but searching for a solution without using momentjs lib. Thanks.
use the same approach but just converting the date in timestamp and comparing both dates in the sort function
Just edited the answer to include a potential solution w/o moment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.