Search code examples
javascriptarrayschunks

How to partition an array, based on specific array combinations?


I have an array and would like to partition them into chunks based on a given combination of values.

For example, I have an array which contains only two different values, Portrait and Landscape.

['Landscape', 'Landscape', 'Portrait', 'Portrait', 'Landscape', 'Portrait']

The conditions I would like it to be partitioned by, would be

  • Chunked array size <= 3.
  • Chunk can only have 'Landscape' <= 2.
  • 'Landscape' and 'Portrait' cannot be in the same chunk.

So, I'd expect an output like:

[['Landscape', 'Landscape'], ['Portrait', 'Portrait'],['Landscape'], ['Portrait']

Solution

  • You could collect the constraints for a new chunk in an array and check if one of the constraints is true and then add a new chunk to the result set.

    var array = ['Landscape', 'Landscape', 'Portrait', 'Portrait', 'Landscape', 'Portrait'],
        constraints = [
            (chunk, v) => v !== chunk[0],
            (chunk, v) => v === 'Landscape' && chunk.length === 2,
            chunk => chunk.length === 3
        ],
        chunks = array.reduce((r, v) => {
            var last = r[r.length - 1];
            if (!last || constraints.some(fn => fn(last, v))) r.push(last = []);
            last.push(v);
            return r;    
        }, []);
    
    console.log(chunks);
    .as-console-wrapper { max-height: 100% !important; top: 0; }