Skip to content

Instantly share code, notes, and snippets.

@jacky810124
Created April 21, 2018 17:08
Show Gist options
  • Save jacky810124/6de25d41554f6dd48ecb40856cb86b78 to your computer and use it in GitHub Desktop.
Save jacky810124/6de25d41554f6dd48ecb40856cb86b78 to your computer and use it in GitHub Desktop.
const days = [
'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
]
const data = {
'mon': [
{
start: '11:00',
end: '22:00'
}
],
'wed': [
{
start: '11:00',
end: '22:00'
}
],
tue: [
{
start: '11:00',
end: '22:00'
}
],
'thu': [
{
start: '11:00',
end: '22:00'
}
],
'fri': [],
'sat': [],
'sun': []
}
let result = []
let lastIndex = 0
days
.forEach((day, index) => {
const currentBusinessHours = data[day]
// push first item into array
if (index === 0) {
return result.push({
businessHours: currentBusinessHours,
days: [ day ]
})
}
const previousDay = days[index - 1]
const previousBusinessHours = data[previousDay]
if (JSON.stringify(previousBusinessHours) === JSON.stringify(currentBusinessHours)) {
return result[lastIndex].days.push(day)
}
lastIndex += 1
return result.push({
businessHours: currentBusinessHours == null
? []
: currentBusinessHours,
days: [ day ]
})
})
console.log(JSON.stringify(result))
// result will be:
// [
// {
// "businessHours": [
// {
// "start": "11:00",
// "end": "22:00"
// }
// ],
// "days": [
// "mon",
// "tue",
// "wed",
// "thu"
// ]
// },
// {
// "businessHours": [],
// "days": [
// "fri",
// "sat",
// "sun"
// ]
// }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment