You're current code is close, but you are caught in your if/while due to your operators. fromDate
must be less than toDate
in order to arrive at any dates in between. If fromDate
is the same as toDate
, let's just return that date so our resulting array does not have mismatched indices.
new Vue({
el: '#app',
vuetify: new Vuetify(),
mounted () {
let arr = [
{id:1,fromDate:'2019-06-01',toDate:'2019-06-03'},
{id:2,fromDate:'2019-10-15',toDate:'2019-10-15'},
{id:3,fromDate:'2019-12-01',toDate:'2019-12-03'},
{id:4,fromDate:'2019-12-25',toDate:'2019-12-26'},
{id:5,fromDate:'2019-12-29',toDate:'2019-12-31'}
]
let tempDates = []
arr.forEach(element => {
let now = moment()
let fromDate = moment(element.fromDate)
let toDate = moment(element.toDate)
dateArray = []
if (fromDate < toDate) {
while (fromDate <= toDate) {
let ld = fromDate.format('YYYY-MM-DD')
dateArray.push(ld)
fromDate = moment(fromDate).add(1,'days');
}
}else {
dateArray.push(fromDate.format('YYYY-MM-DD'))
}
tempDates.push(dateArray)
})
console.log(tempDates);
},
})
In this solution have also added an array within the forEach in order to collect the relevant dates from each item and keep them separate, which is then pushed to the tempDates array. The output of this code is:
[["2019-06-01", "2019-06-02", "2019-06-03"], ["2019-10-15"], ["2019-12-01", "2019-12-02", "2019-12-03"], ["2019-12-25", "2019-12-26"], ["2019-12-29", "2019-12-30", "2019-12-31"]]
See the CodePen here: Solution
Of course you could choose to format your output data however you please, I have separated the information since no schema for the output was specified in detail.
Note: You could also ditch the forEach
and use reduce()
to achieve this. In this answer I have stuck with your original code style and approach, which isn't wrong, but, there are alternative approaches.