Created
April 21, 2018 17:08
-
-
Save jacky810124/6de25d41554f6dd48ecb40856cb86b78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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