Home > Software design >  Grouping arrays based on duration string
Grouping arrays based on duration string

Time:08-31

I need to group elements in different containers based on overlapping periods. Let's say we have the following array:

const periods = ['1-4', '1-7', '1-4', '1-8', '1-8', '5-8', '9-12', '9-12'];

I need it to turn into:

[['1-4', '5-8', '9-12'], ['1-7', '9-12'], ['1-4'], ['1-8'], ['1-8']]

Basically, elements get pushed into a "row". If the element's period overlaps with another inside the current row, it would create another one.

In this example '1-4', '5-8' and '9-12' are grouped because their periods do not overlap.

I'm doing this with DOM elements, I used arrays in an attempt to simplify things. Any ideas?

CodePudding user response:

You could find the group with checking the last value against the start value.

const
    periods = ['1-4', '1-7', '1-4', '1-8', '1-8', '5-8', '9-12', '9-12'],
    groups = periods.reduce((r, p) => {
        const
            start =  p.split('-', 1),
            t = r.find(a =>  a.at(-1).split('-')[1] < start);
            
        if (t) t.push(p);
        else r.push([p]);
        return r;
    }, []);

console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related