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.

40 thoughts on “Previous closest date from array of object”

  1. 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)
    Reply

Leave a Comment