首页 > 解决方案 > 检查日期是否与今天的开始日期在数组中连续

问题描述

我正在尝试检查以下数组中的日期是否与今天的开始日期(07/01/2020)连续。

var arrayDate = [
  '06/30/2020', '06/29/2020', '06/28/2020', '06/26/2020'
]

它应该返回

var nbDatesConsecutives = 3

另一方面,以下示例应返回 0 :

var arrayDate = [
  '06/29/2020', '06/28/2020', '06/26/2020', '06/25/2020'
]

我已经尝试了很多次来解决它,但我仍然阻止了它。这是我的尝试之一:

let arrayDiff = []
arrayDate.map((element, i) => {
    arrayDiff.push(today.diff(moment(element), 'days'));
});
let previousValue = null;
arrayDiff.map((element, i) => {
    let currentValue = arrayDiff[i];
    if (i > 0) {
      if (currentValue > previousValue) {
        strike++;
      }
    }
    previousValue = currentValue;
})

谢谢 !

标签: javascriptarraysdatecomparisonmomentjs

解决方案


您映射到当天差异的想法很好。让我以此为基础:

你可以...

  • 获取“今天”作为当天的开始
  • 将日期映射到它们与今天的差异,以天为单位
  • 找到第一个数组索引,其中该差异不再等于索引加一(因为您希望[1, 2, 3, 4]在完美情况下像这样的数组,所以例如array[2]= 2 + 1= 3
  • 第一个不匹配的索引已经是您的结果,除非整个数组具有预期的日期,因此没有索引会不匹配 - 在这种情况下,您返回数组的长度

在这里你可以看到它的工作:

function getConsecutive (dates) {
  // Note: I hardcoded the date so that the snippet always works.
  // For real use, you need to remove the hardcoded date.
  // const today = moment().startOf('day')
  const today = moment('2020-07-01').startOf('day')

  const diffs = dates.map(date => today.diff(moment(date, 'MM/DD/YYYY'), 'days'))
  const firstIncorrectIndex = diffs.findIndex((diff, i) => diff !== i + 1)
  return firstIncorrectIndex === -1 ? dates.length : firstIncorrectIndex
}

// Outputs 4:
console.log(getConsecutive(['06/30/2020', '06/29/2020', '06/28/2020', '06/27/2020']))

// Outputs 3:
console.log(getConsecutive(['06/30/2020', '06/29/2020', '06/28/2020', '06/26/2020']))

// Outputs 0:
console.log(getConsecutive(['06/29/2020', '06/28/2020', '06/26/2020', '06/25/2020']))
<script src="https://momentjs.com/downloads/moment.js"></script>


推荐阅读