在开发中遇到了联查的问题,刚开始写了很多代码,后面大佬教我简化了,做下笔记。
求两个数组的交集

let arr1 =[0,2,4,5,7]
let arr2 = [0,3,5,6,8,4,9,55]
var newarr = arr1 .filter((v) => arr2 .includes(v))
//也可以用,不考虑(数组中不含NaN)
newarr = arr1.filter((v)=> arr2.indexOf(v)>-1 )
//filter方法是返回一个符合过滤条件的新数组,不改变原有的数组

求并集

arr1.concat(arr2.filter(function(v) {
return arr1.indexOf(v) === -1})) // [1,2,3,4,5]

求差集

newarr= a.filter(function(v){
 		return b.indexOf(v) === -1
  }).concat(b.filter(function(v){ return a.indexOf(v) === -1 }))

应用 :在elemen-ui中select组件使用它来做过滤筛选符合条件的数据
需求:两个筛选联查(即求分别符合单个条件的两个数组的交集)
在这里插入图片描述

 <!-- 筛选状态 -->
        <el-select
          v-model="stateValue"
          placeholder="状态筛选"
          size="medium"
          @change="stateChange"
        >
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <!-- 批次筛选 -->
        <el-select
          v-model="taskEpoch"
          placeholder="批次筛选"
           size="medium"
          @change="taskEpochChange"
        >
          <el-option
            v-for="item in taskEpochOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
//stateList 和 taskEpochList 是用来存放单独符合条件的数据数组,最后再进行交集查询,做交集查询时都不能为空数组
	// 统计状态筛选
      stateChange(index) {
        this.stateList = this.totalList.filter((i) => {
          if (i.task_status == index || index == '5') {
            return true
          }
        })
	// 最后求交集
        this.list = this.stateList.filter((v) => this.taskEpochList.includes(v))
      },
     // 批次
      taskEpochChange(index) {
        this.taskEpochList = this.totalList.filter((i) => {
          if (i.task_epoch == index || index == '0') {
            return true
          }
        })
        //交集
        this.list = this.stateList.filter((v) => this.taskEpochList.includes(v))
      },
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐