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

Grouping arrays based on duration string

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.

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

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?

>Solution :

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; }
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