简体   繁体   中英

Previous closest date from array of object

var dateArray = ['11/01/2020', '10/01/2020', '09/01/2020', '07/01/2020', '06/01/2020']

If I have a date 08/01/2020 , then I need to find its previous closest date in the array which is 07/01/2020 . I am omitting the time but that will also be part of the date.

 var dateArray = ['11/01/2020', '10/01/2020', '09/01/2020', '07/01/2020', '06/01/2020'] let date = '08/01/2020' function findClosestPrevDate(arr,target){ let targetDate = new Date(target); let previousDates = arr.filter(e => ( targetDate - new Date(e)) > 0) let sortedPreviousDates = previousDates.filter((a,b) => new Date(a) - new Date(b)) return sortedPreviousDates[0] || null } let r1 = findClosestPrevDate(dateArray,"08/01/2020") console.log(r1) let r2 = findClosestPrevDate(dateArray,"10/01/2020") console.log(r2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM