Skip to content
Advertisement

Get data from array based on time intervals [closed]

I have an array like this,

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] },
]

I want to return data based on time intervals, that is like, say the interval is 2 minutes and the time of the first element is 11:00 am then only the elements of the array with time 11:02 am, 11:04 am, 11:06 am. etc. If the interval is 3 minutes, then elements with time 11:03 am, 11:06 am… should be returned. I have tried different methods. It is not working. Can you guys help me with a solution with more efficiency?

If you didn’t understand my question,

Elements in the array

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)

If I set the time interval as 2 minutes

The records should be returned like this

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)

Advertisement

Answer

a reduce method makes this pretty simple

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement