对象数组中的上一个最近日期
Previous closest date from array of object
var dateArray = ['11/01/2020', '10/01/2020', '09/01/2020', '07/01/2020', '06/01/2020']
如果我有一个日期 08/01/2020
,那么我需要在数组中找到它之前最接近的日期 07/01/2020
。我省略了时间,但这也是日期的一部分。
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)
var dateArray = ['11/01/2020', '10/01/2020', '09/01/2020', '07/01/2020', '06/01/2020']
如果我有一个日期 08/01/2020
,那么我需要在数组中找到它之前最接近的日期 07/01/2020
。我省略了时间,但这也是日期的一部分。
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)