You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于多值过滤数组所有组合的Typescript实现问题

实现多选属性的组合筛选

首先调整筛选逻辑核心:将单个值的匹配改成数组包含判断,同时确保选中项的默认状态为空数组(而非单个值或null)。

修改后的过滤代码

假设this.selectedFilter中每个属性都是多选后的数组(比如Color: ["Yellow","Blue","Red"],空数组表示不筛选该属性),修改过滤逻辑如下:

this.combinations = this.combinations.filter(x => 
  // 颜色筛选:若有选中颜色,当前项Color需在选中数组内;无选中则跳过该条件
  (!this.selectedFilter.Color.length || this.selectedFilter.Color.includes(x.Color)) &&
  // 容量筛选逻辑同理
  (!this.selectedFilter.Capacity.length || this.selectedFilter.Capacity.includes(x.Capacity)) &&
  // 类型筛选逻辑同理
  (!this.selectedFilter.Type.length || this.selectedFilter.Type.includes(x.Type))
);

关键说明

  1. 选中项初始化:确保this.selectedFilter的初始值为每个属性对应空数组,避免判断出错:
    this.selectedFilter = {
      Color: [],
      Capacity: [],
      Type: []
    };
    
  2. 逻辑判断:
    • 当某属性的选中数组为空(length === 0),表示不对该属性做筛选,直接返回true;
    • 当选中数组有值时,检查当前项的对应属性是否存在于选中数组中,符合则返回true。

示例效果

当选中Color: ["Yellow","Blue","Red"]、Capacity: ["16GB","32GB"]、Type: ["Normal"]时,会筛选出所有满足以下条件的组合:

  • Color是Yellow/Blue/Red中的任意一个
  • Capacity是16GB/32GB中的任意一个
  • Type为Normal

内容的提问来源于stack exchange,提问作者Forey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 11:09:56