如何根据特定的数组组合对数组进行分区?

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

我有一个数组,想根据给定的值组合将它们分成块。

例如,我有一个只包含两个不同值的数组,Portrait 和 Landscape。

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

我希望它被分区的条件是

所以,我希望输出如下:

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

您可以在数组中收集新块的约束,并检查其中一个约束是否为 true,然后将新块添加到结果集中。

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