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

React Native中实现多条件过滤数组交集的问题求助

React Native 多条件交集过滤运动课程数组问题修复

原代码存在的核心问题

  • 过滤逻辑顺序错误:先执行分类过滤循环,再用allFilterCategory覆盖结果,导致当allFilterCategory为true时前面的循环完全无效;若过滤变量全为空,filteredListCategory会变成空数组,后续交集判断为空就返回全量列表,完全不符合需求。
  • 未处理过滤变量为空的场景:原代码直接将课程属性与过滤变量硬匹配,若过滤变量为空(关闭过滤项),对应过滤列表会为空,最终交集为空时返回全量,这是错误的——关闭过滤项意味着该条件不参与过滤,而非过滤掉所有内容。
  • 冗余分支判断:用多个else if枚举所有类别/等级,代码冗余且新增类别时需要修改大量代码,维护成本高。
  • 交集实现效率低:先分别过滤两个列表再取交集,不如一次遍历同时判断所有条件,逻辑更清晰且性能更优。

优化后的实现方案

根据需求(过滤变量为空则忽略该条件,多条件同时选中时取交集),可以简化为一次遍历完成过滤:

function filterIntersect() {
  return list.filter(item => {
    // 类别过滤:若所有类别过滤变量都为空,直接通过;否则匹配任意开启的类别
    const matchesCategory = !cardio && !yoga && !boxing && !dance && !pilates && !stretching 
      ? true 
      : (item.category.toLowerCase() === cardio || 
         item.category.toLowerCase() === yoga || 
         item.category.toLowerCase() === boxing || 
         item.category.toLowerCase() === dance || 
         item.category.toLowerCase() === pilates || 
         item.category.toLowerCase() === stretching);
    
    // 等级过滤:逻辑同类别过滤
    const matchesLevel = !beginnerFilter && !intermediateFilter && !advancedFilter
      ? true
      : (item.level.toLowerCase() === beginnerFilter || 
         item.level.toLowerCase() === intermediateFilter || 
         item.level.toLowerCase() === advancedFilter);
    
    // 同时满足所有开启的过滤条件(交集)
    return matchesCategory && matchesLevel;
  });
}

更易维护的进阶优化

如果把过滤变量整理成数组(比如用selectedCategories存储选中的类别,空数组表示关闭类别过滤),代码会更简洁灵活:

// 假设过滤变量已整理为:
// selectedCategories: 选中的类别数组,空数组则不过滤类别
// selectedLevels: 选中的等级数组,空数组则不过滤等级

function filterIntersect() {
  return list.filter(item => {
    const matchesCategory = selectedCategories.length === 0 
      ? true 
      : selectedCategories.includes(item.category.toLowerCase());
    
    const matchesLevel = selectedLevels.length === 0
      ? true
      : selectedLevels.includes(item.level.toLowerCase());
    
    return matchesCategory && matchesLevel;
  });
}

关键逻辑说明

  • 当某类过滤项全部关闭(对应变量全为空或选中数组为空),该条件直接返回true,不参与过滤。
  • 仅当过滤项开启时,才校验课程是否匹配对应条件。
  • 最终返回同时满足所有开启过滤条件的课程(交集),不会出现误返回全量列表的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:06:40