I am trying to group weekdays together based on the property value in an array. I have used lodash to obtain a solution. My code looks like this,
const array = [{
weekDay: 'Monday',
hoursInfo: '11:00am-8:00pm',
},
{
weekDay: 'Tuesday',
hoursInfo: '11:00am-8:00pm',
},
{
weekDay: 'Wednesday',
hoursInfo: '9:00am-11:00am',
},
{
weekDay: 'Thursday',
hoursInfo: '11:00am-8:00pm',
},
{
weekDay: 'Friday',
hoursInfo: '11:00am-9:00pm',
},
{
weekDay: 'Saturday',
hoursInfo: '11:00am-9:00pm',
},
{
weekDay: 'Sunday',
hoursInfo: 'Closed',
},
];
const result = _.chain(array).groupBy("hoursInfo").value();
document.getElementById("result").innerHTML = JSON.stringify(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<div id="result"></div>
I am able to group the list of weekdays which has the same timings together, but my requirement is to group them in a sequence. My expected output is something like this,
Monday-Tuesday: 11:00am-8:00pm
Wedesday: 9:00am-11:00am
Thursday: 11:00am-8:00pm
Friday-Saturday: 11:00am-9:00pm
Sunday: Closed
Please help me with a better approach
>Solution :
Reduce will work
const newArr = array.reduce((acc, item) => {
if (acc.length && acc[acc.length - 1].hoursInfo === item.hoursInfo) {
acc[acc.length - 1].weekDay += `- ${item.weekDay}`;
} else acc.push(item);
return acc;
}, [])
.map(item => `${item.weekDay}: ${item.hoursInfo}`);
console.log(newArr)
<script>
const array = [
{ weekDay: 'Monday', hoursInfo: '11:00am-8:00pm' },
{ weekDay: 'Tuesday', hoursInfo: '11:00am-8:00pm' },
{ weekDay: 'Wednesday',hoursInfo: '9:00am-11:00am' },
{ weekDay: 'Thursday', hoursInfo: '11:00am-8:00pm' },
{ weekDay: 'Friday', hoursInfo: '11:00am-9:00pm' },
{ weekDay: 'Saturday', hoursInfo: '11:00am-9:00pm' },
{ weekDay: 'Sunday', hoursInfo: 'Closed'}
];
</script>