【问题标题】:Check if dates consecutives in array with starting date today检查数组中的日期是否与今天的开始日期连续
【发布时间】:2020-10-21 23:40:56
【问题描述】:

我正在尝试检查以下数组中的日期是否与今天的开始日期 (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;
})

谢谢!

【问题讨论】:

  • 您的示例几乎不是所有未定义变量的尝试,请尝试至少提供一个您尝试过的可编译示例。

标签: javascript arrays date comparison momentjs


【解决方案1】:

您正在做的错误是 1) currentValue > previousValue 相反,您应该检查差异,它必须是 1,如果不是 1,则打破循环。所以,这里出现了错误 2)你使用的是 map 函数而不是使用简单的 for 循环,这样你就可以中断。

`

function getConsecutiveDateCount(arrayDate) {
    let arrayDiff = [];
    let today = moment();

    arrayDate.map((element, i) => {
      arrayDiff.push(today.diff(moment(element), 'days'));
    });

    let strike = 0;

    arrayDiff.unshift(0); /// insert 0 for today

    let previousValue = arrayDiff[0];
    for (let i = 1; i < arrayDiff.length; i++) {
      currentValue = arrayDiff[i];

      if (currentValue - previousValue === 1) {
        strike++;
      } else {
        break;
      }

      previousValue = currentValue;
    }

    return strike;
  }

`

【讨论】:

    【解决方案2】:

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

    你可以...

    • 获取“今天”作为当天的开始
    • 将日期映射到它们与今天的差异,以天为单位
    • 找到第一个数组索引,其中这个差不再等于索引加一(因为您期望在完美情况下像[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']))
    &lt;script src="https://momentjs.com/downloads/moment.js"&gt;&lt;/script&gt;

    【讨论】:

    • 不错!谢谢你的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 2018-04-05
    • 2011-09-26
    • 1970-01-01
    • 2016-03-06
    相关资源
    最近更新 更多