检查日期中连续的日期是否与今天开始的日期连续

时间:2020-07-01 13:44:45

标签: javascript arrays date comparison momentjs

我正在尝试检查以下数组中的日期是否是从今天(2020年1月1日)开始的连续日期。

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;
})

谢谢!

2 个答案:

答案 0 :(得分:1)

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

你可以...

  • 将“今天”作为当天的开始
  • 将日期与当前日期(以天为单位)进行映射
  • 找到第一个数组索引,其中的差异不再等于索引加一个(因为在理想情况下,您期望像[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>

答案 1 :(得分: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;
  }

`