• js filter,every,includes 过滤数组


    背景:

         页面:在项目中遇到的,前端页面显示为,顶部是下拉搜索条件,下面是一个表格;

         数据:接口请求一次性拿到所有:搜索条件里的下拉选项和表格中的数据;

         现状:需要前端在搜索条件时,筛选表格数据展示,在前端进行筛选;

        为什么不在后端进行筛选?

        答:在某个页面中,接口已经把所有进行数据都返回前端展示了,现在的页面只是多了筛选查看,后端不想再提供接口,让前端还是调用之前的接口进行处理。

      案例一

    1.   let arr = [
    2.       {
    3.         type: 'uddaas,xiao',
    4.         name: '红色,小',
    5.       },
    6.       {
    7.         type: 'ffoop,da',
    8.         name: '黄色,大',
    9.       },
    10.       {
    11.         type: 'hhhugd,da',
    12.         name: '绿色,大',
    13.       },
    14.     ]
    15.     console.log('原始数据:', arr)
    16.     let str1 = ['ffoop','da']
    17.     
    18.  

       先过滤,再把指定字符串转换为数组,再通过数组比对,返回true或false,查找到对应的数据;

    1.   let results1 = arr.filter( (v) => {
    2.       // filter过滤数组
    3.       // 字符串转换数组
    4.       let typesId = v.type.split(','
    5.       return str1.every((e) => {
    6.         // every查找符合的元素
    7.         // includes判断数组是否包含指定的值,有则返回true,否则返回false
    8.         return typesId.includes(e)
    9.       })
    10.     })
    11.     console.log('results1:',results1)
    12. //     {
    13. //     "type": "ffoop,da",
    14. //     "name": "黄色,大"
    15. // }

        案例二
       

    1. let arr1 = [12,13,14,15,16]
    2.     let iniArr = []
    3.     let arr2 = [1000,2000,3000]
    4.     let obj1 = [
    5.       {
    6.         arr: [1000,2000,3000],
    7.         title: '数字信息',
    8.       },
    9.       {
    10.         arr: [1100,2100,3100],
    11.         title: '数字信息1',
    12.       },
    13.       {
    14.         arr: [1200,2200,3200],
    15.         title: '数字信息2',
    16.       },
    17.     ]


         通过filter过滤,在过滤中使用every查找,并通过includes验证是否有符合的数据,有则返回true,否则返回false
      

    1.   let filterObj = obj1.filter((v1) => {
    2.       return iniArr.every((e1) => {
    3.         return v1.arr.includes(e1)
    4.       })
    5.     })
    6.     console.log('filterObj:',filterObj)  
    7.     // {
    8. //     "arr": [
    9. //         1100,
    10. //         2100,
    11. //         3100
    12. //     ],
    13. //     "title": "数字信息1"
    14. // }

    不足:在写这部分需求时,花费了较长时间,没有想到filter,every和includes的处理思路,请教了同事后才解决,自己的基础知识还需要打磨。

  • 相关阅读:
    白鹭群优化算法(ESOA)附matlab代码
    安防监控视频汇聚平台EasyCVR视频广场搜索异常,报错“通道未开启”的问题排查与解决
    CMake中foreach的使用
    重制版 day 15 文件操作
    谷粒商城 (十二) --------- 商品服务 API 三级分类 ③ 树形展示三级分类数据
    Visual Studio使用——vs解决方案显示所有文件
    Springboot打包部署到linux服务器的方法
    【微机接口】串行通信基础
    小白学python系列————【Day50】选课系统项目
    Python 动态建模(1)
  • 原文地址:https://blog.csdn.net/weixin_42400404/article/details/136164871