【问题标题】:How to partition an array, based on specific array combinations?如何根据特定的数组组合对数组进行分区?
【发布时间】:2019-05-22 13:14:40
【问题描述】:

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

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

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

我希望它被划分的条件是

  • 分块数组大小
  • 块只能有“横向”
  • “风景”和“人像”不能在同一个区块中。

所以,我希望输出如下:

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

【问题讨论】:

  • sort 通常的意思是把一个数组按指定的顺序排列。我认为您想根据规则分区
  • 循环遍历数组并分组匹配元素。我建议使用 Array.prototype.reduce,但 for 循环可能更容易开始。

标签: javascript arrays chunks


【解决方案1】:

您可以在数组中收集新块的约束并检查其中一个约束是否为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; }

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 2023-01-11
    • 2020-06-29
    • 2021-09-12
    • 2022-01-19
    • 2021-07-08
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多