From an array:
["01/01/2015", "02/01/2015", "03/01/2015", "05/01/2015", "06/01/2015"];
to
[{start_date: "01/01/2015", end_date: "03/01/2015"}, { start_date: "05/05/2015", end_date: "06/01/2015 }];
Is there a library available for this type of functions?
I would like to convert the first array dates to an array of objects that represent time intervals.
PS: date format in the question is dd-MM-yyyy
const strings = ["01/01/2015", "02/01/2015", "03/01/2015", "05/01/2015", "06/01/2015"];
const dates = strings.map(str => ({
date: new Date(str.split(/\//g).reverse().join('-') + 'T00:00:00Z'),
string: str
}))
let current = { start_date: dates[0].string }
const intervals = [current]
for (let i = 1; i < dates.length; i += 1) {
const diff = (dates[i].date - dates[i - 1].date) / (1000 * 60 * 60 * 24)
if (diff === 1) {
current.end_date = dates[i].string
} else {
current = { start_date: dates[i].string }
intervals.push(current)
}
}
console.log(intervals)