【问题标题】:Filter array by property and other array按属性和其他数组过滤数组
【发布时间】:2021-03-17 17:46:19
【问题描述】:

我有一个计划,有多个项目。 我的对象是这样的:

planning: [
  { id: '1', equipe: [ '1', '2' ] },
  { id: '2', equipe: [ '1' ] },
  { id: '3', equipe: [ '2', '3' ] }
  ...
]

我想过滤这个数组来隐藏或显示计划项目。 我显示的数组是:

checked: [ '1', '4' ]

所以,阵列规划可以通过equipe阵列过滤,所以应该是:

planning: [
  { id: '1', equipe: [ '1', '2' ] },
  { id: '2', equipe: [ '1' ] }
]

我尝试过滤数组,但我看不到 indexOf 如何处理数组而不是字符串。 我也尝试过包含功能,但这不起作用:

planning.filter(item => checked.includes(item.equipe))

求帮助!

【问题讨论】:

  • planning.filter(item => checked.includes(item.equipe)) 在这种情况下,您不是检查已检查数组中的任何元素是否存在于equipe 中,而是检查已检查是否包含equipe 数组本身。
  • 那我该怎么办?
  • 在下面添加了我的实现作为答案。

标签: arrays reactjs filter


【解决方案1】:

您需要针对checked 遍历item.equipe 中的每个值,您可以使用some 检查是否至少有一个匹配checked 数组:

planning.filter(item => item.equipe.some(val => checked.includes(val)))

const planning = [
  { id: '1', equipe: [ '1', '2' ] },
  { id: '2', equipe: [ '1' ] },
  { id: '3', equipe: [ '2', '3'] }
]
   
const checked = [ '1', '4' ]
   
const filtered = planning.filter(item => item.equipe.some(val => checked.includes(val)))
   
console.log(filtered)

【讨论】:

    【解决方案2】:

    我会以这种方式实现逻辑。

    //Original Data
    let planning = [
        { id: '1', equipe: ['1', '2'] },
        { id: '2', equipe: ['1'] },
        { id: '3', equipe: ['2', '3'] }
    ]
    
    /**
     * Converting checked into Set so it will maintain all the unique values.
     * I can check which elements are present in O(1) using checked.has(value)
     */
    let checked = new Set(['1', '4'])
    
    
    /**
     * Using standard filter() function. 
     * Using some() to check if atleast 1 element from equipe is present in Set. 
     * If yes then checked.has(element) evaluates to true and some() receives atleast 1 element is valid and the element passes the filter.
     */
    
    let filtered = planning.filter(plan => {
        return plan.equipe.some(element => checked.has(element));
    })
    
    console.log(filtered)

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 2016-08-10
      • 2016-09-20
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多