我有一个数组,想根据给定的值组合将它们分成 block 。
例如,我有一个数组,其中仅包含两个不同的值:纵向和横向。
['Landscape', 'Landscape', 'Portrait', 'Portrait', 'Landscape', 'Portrait']
我希望对其进行分区的条件是
- 分块数组大小 <= 3。
- block 只能有“横向”<= 2。
- “横向”和“纵向”不能位于同一 block 中。
所以,我期望的输出如下:
[['Landscape', 'Landscape'], ['Portrait', 'Portrait'],['Landscape'], ['Portrait']
最佳答案
您可以收集数组中新 block 的约束,并检查其中一个约束是否为true
,然后将新 block 添加到结果集中。
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; }
关于javascript - 如何根据特定的数组组合对数组进行分区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56257724/