0

我需要使用 DateFNS v.2.0.1 nearestIndexTo从日期数组中获取最接近的日期。我目前正在返回 NaN。我在这里想念什么?

(val = 2019-09-01) 
(arrDates = 2019-09-01,2019-09-03,2019-09-03,2019-09-04,2019-09-05,2019-09-05,2019-09-23,2019-10-01,2019-11-18)

getClosestToDate(val,arr) {
  var arrDates = [_.map(arr, 'date')]
  var closestDate = closestIndexTo(parseISO(val), arrDates)
  return closestDate
},
4

1 回答 1

0

所以基本上日期应该首先是字符串。下一个可能不正确的地方是你使用[_.map(arr, 'date')]的地方,实际上将 map 的结果放入数组中,使其成为双数组。此外,为了解析arrDate对象,您需要映射 arr 值才能parseISO起作用。所以下面的代码应该可以工作

var closestIndexTo = require('date-fns/closestIndexTo')
var parseISO = require('date-fns/parseISO')
var _ = require('lodash')

val = "2019-10-04"
arrDates = ["2019-09-01","2019-09-03","2019-09-03","2019-09-04","2019-09-05","2019-09-05","2019-09-23","2019-10-01","2019-11-18"]

function getClosestToDate(val, arr) {
  var arrDates = _.map(arr, (a) => parseISO(a))
  var closestDate = closestIndexTo(parseISO(val), arrDates)
  return closestDate
}

console.log("result", getClosestToDate(val, arrDates))

这是repl的链接

于 2019-09-06T19:15:29.403 回答