Fatih Aktepe Fatih Aktepe - 1 year ago 32
Node.js Question

NodeJS combining object array range properties

the title may be a bit confusing but I'll explain it in detail. I have a table in UI and user can choose date ranges from there like;

monday - {in:"13:00:00",out:"13:59:59"}

tuesday - [{in:"13:00:00",out:"13:59:59"},{in:"14:00:00",out:"14:59:59"}]

user can only choose multiple hour intervals for one day. I already made the grouping the intervals according to their date and combining the intervals like

tuesday- [{in:"13:00:00",out:"14:59:59"},{in:"14:00:00",out:"14:59:59"}]

in the first iteration. But I couldn't figure out how to make it for more than 4 or 5 hour intervals.FYI I'm using lodash for sorting and grouping and moment for converting hours to int.

If user enters 5 intervals for tuesday like [{in:"13:00:00",out:"13:59:59"},{in:"14:00:00",out:"14:59:59"},{in:"15:00:00",out:"15:59:59"},{in:"18:00:00",out:"18:59:59"},{in:"19:00:00",out:"19:59:59"}]

I want ranges to be combined like ;


Any help or suggestion will be appreciated.


Assuming that your input data is chronological then one way of implementing your reduced time table is this;

var timeSlices = [{in:"13:00:00",out:"13:59:59"},{in:"14:00:00",out:"14:59:59"},{in:"15:00:00",out:"15:59:59"},{in:"18:00:00",out:"18:59:59"},{in:"19:00:00",out:"19:59:59"}],
            ts = new Date(),
            te = new Date(),
       reduced = timeSlices.reduce((p,c) => {p.length ? (ts.setHours(...p[p.length-1].out.split(":")),
                                                         te-ts <= 1000 ? p[p.length-1].out = c.out
                                                                       : p.push(c))
                                                      : p.push(c);
                                             return p;},[]);

However if the objects with in and out times are located arbitrary in the array then a more conceptual approach like first sorting them according to their in times would be essential. That wouldn't be a big deal though.