简体   繁体   English

Javascript:从数组中获取连续的天数?

[英]Javascript: Getting consecutive days from an array?

I have an array of ISO dates, ["2019-09-10", "2019-09-14", "2019-09-11", "2019-09-22","2019-09-25"];我有一组 ISO 日期, ["2019-09-10", "2019-09-14", "2019-09-11", "2019-09-22","2019-09-25"]; I am trying to find the best approach to return an array of objects that are pairs.我试图找到返回成对对象数组的最佳方法。 For example:例如:

let results: [
   {start: 2019-09-10, end: 2019-09-11},
]

I tried using milliseconds to compare but it seems to just return the same day as well, {start: 2019-09-11, end: 2019-09-11}我尝试使用毫秒进行比较,但它似乎也在同一天返回, {start: 2019-09-11, end: 2019-09-11}

One way to do this is to first sort the elements by dates, then compare them pairwise to see if they are consecutive.一种方法是首先按日期对元素进行排序,然后将它们成对比较以查看它们是否连续。 In the example below, I use the date-fns to parse them and make comparing them easier, but you could probably make do without it.在下面的示例中,我使用date-fns来解析它们并使它们更容易进行比较,但是您可能没有它也可以。

The real key takeaway is sorting the elements, then reducing over them.真正的关键要点是对元素进行排序,然后对它们进行归约。 The reducer function can take more than just the accumulator and the currentValue ; reducer function 可以接受的不仅仅是accumulatorcurrentValue you can also get the index and the array being iterated over.您还可以获得索引和正在迭代的数组。 The latter two make it easy to look up the next element, and compare it to see if something should be added to the accumulator .后两者使查找下一个元素变得容易,并比较它以查看是否应将某些内容添加到accumulator中。

const addDays = require('date-fns/addDays')
const parse = require('date-fns/parseISO')

const dates = ["2019-09-10", "2019-09-14", "2019-09-11", "2019-09-22","2019-09-25"]

//First, we map them to date objects, and sort the new list.
const sorted = dates.map(d => parse(d)).sort((a,b) => a-b)

//Then we reduce over the entire list, checking pairwise for the dates to be consecutive
const pairs = sorted.reduce((pairs, start, i, dates) => {
  const end = dates[i+1]
  if (addDays(start, 1)-end === 0) pairs.push({start, end})
  return pairs
}, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM