Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group array Elements in a sequence JavaScript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading