根据时间间隔从数组中获取数据

Get data from array based on time intervals

我有一个这样的数组,

const data =[
    { date: 2022-04-11T15:08:54.223Z, coordinates: [Object] },
    { date: 2022-04-11T15:09:36.078Z, coordinates: [Object] },
    { date: 2022-04-11T15:18:18.405Z, coordinates: [Object] },
    { date: 2022-04-11T15:19:45.228Z, coordinates: [Object] },
    { date: 2022-04-11T15:21:00.188Z, coordinates: [Object] },
]

我想 return 基于时间间隔的数据,也就是说,假设间隔是 2 分钟,第一个元素的时间是 11:00 am 然后只有数组的元素随着时间 11:02 上午,11:04 上午,11:06 上午。等。如果间隔为 3 分钟,则时间为 11:03 am、11:06 am... 的元素应该被 returned。我尝试了不同的方法。它不工作。你们能帮我出一个更高效的解决方案吗?

如果你不明白我的问题,

数组中的元素

Element  :: Mon Apr 11 2022 20:39:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:40:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:41:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:42:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:43:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:44:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:45:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:46:36 GMT+0530 (India Standard Time)

如果我设置时间间隔为2分钟

记录应该return这样编辑

Element  :: Mon Apr 11 2022 20:39:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:41:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:43:36 GMT+0530 (India Standard Time)
Element  :: Mon Apr 11 2022 20:45:36 GMT+0530 (India Standard Time)

reduce 方法使这变得非常简单

let interval = 3, 
  firstDate;
let intervalArr = data.reduce((acc,entry)=>{
 let date = new Date(entry.date) // should condition this in case prop is a string and not datetime, but should work as is
 firstDate ||= date
 let minutesSinceFirst = ~~((firstDate - date) / 60000) 

 // modulus will be 0 if min is divisible by interval
 if (minutesSinceFirst % interval === 0)
   acc.push(entry)  // push to accumulator

 return acc
}, []) // accumulator starts as an empty array

firstDate = null