I have an array of days and the opening hours:
let arrData = [
{
"dayOfTheWeek":"Monday",
"isOpen":true,
"hoursOfBusiness":[
{
"opensAt":"10:00:00",
"closesAt":"15:00:00"
}
]
},
{
"dayOfTheWeek":"Tuesday",
"isOpen":true,
"hoursOfBusiness":[
{
"opensAt":"10:00:00",
"closesAt":"15:00:00"
}
]
},
{
"dayOfTheWeek":"Wednesday",
"isOpen":true,
"hoursOfBusiness":[
{
"opensAt":"10:00:00",
"closesAt":"15:00:00",
}
]
},
{
"dayOfTheWeek":"Thursday",
"isOpen":true,
"hoursOfBusiness":[
{
"opensAt":"09:00:00",
"closesAt":"16:00:00",
}
]
},
{
"dayOfTheWeek":"Friday",
"isOpen":true,
"hoursOfBusiness":[
{
"opensAt":"10:00:00",
"closesAt":"14:00:00",
}
]
},
{
"dayOfTheWeek":"Saturday",
"isOpen":false,
"hoursOfBusiness":[]
},
{
"dayOfTheWeek":"Sunday",
"isOpen":false,
"hoursOfBusiness":[]
}
]
And I want to combine the days where the opening hours are the same. So, basically my goal is to display the opening hours like this:
Monday-Wednesday: 10-15
Thursday: 9-16
Friday: 10-14
So, I tried to to this:
function openingHours(data){
let merged = [];
let idx = -1;
for (let i = 0; i < data.length; i++) {
let day = data[i];
if (
idx == -1 ||
merged[idx].hoursOfBusiness.opensAt != day.hoursOfBusiness.opensAt
) {
merged.push({
days: day.dayOfTheWeek,
opensAt: day.hoursOfBusiness.opensAt,
closesAt: day.hoursOfBusiness.closesAt,
});
idx++;
} else {
merged[idx].days.push(day.dayOfTheWeek);
}
}
return merged;
}
but this doesn't really work. I have created a JSFIDDLE so please check it out.
Can someone help me out?
UPDATE
All answers were pretty useful but actually I need a different output after all, since the opening/closing hours can vary, I need something like:
data: [
{
days: "Monday-Wednesday",
opensAt: "10:00",
closesAt: "15:00
},
{
days: "Thursday",
opensAt: "09:00",
closesAt: "16:00
},
{
days: "Friday",
opensAt: "10:00",
closesAt: "14:00
},
]
I hope someone could help me out?