【问题标题】:How to filter a JS array with user defined number of filters?如何使用用户定义的过滤器数量过滤 JS 数组?
【发布时间】:2022-12-18 17:36:48
【问题描述】:

我有一个要过滤的对象的配置文件数组。过滤器是另一个数组中状态的组合。状态数组由用户定义。 Profiles 数组可以由用户使用一个或多个 Status 进行过滤。在不知道应该提前检查多少条件的情况下如何编写过滤函数?

//the array to filter
let profileList = [{name: "John", staus: "green"}, {name: "Alex", staus: "yellow"}, {name: "Jane", staus: "green"}]

//user defined: they can add up to 30 statuses
let statusList = ["green", "yellow", "red", "black"]

//also user defined: they can filter by as many statuses as they want
let filters = ["green", "red"]

  
const filteredProfileList = profileList.filter(element => {
  return //how to write the conditions with logical OR (||) if I don't know how many statuses will be used?
});
    


【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    你不需要知道有多少将被检查,你可以只检查过滤器数组是否包含配置文件状态:

    //the array to filter
    let profileList = [{name: "John", staus: "green"}, {name: "Alex", staus: "yellow"}, {name: "Jane", staus: "green"}]
    
    //user defined: they can add up to 30 statuses
    let statusList = ["green", "yellow", "red", "black"]
    
    //also user defined: they can filter by as many statuses as they want
    let filters = ["green", "red"]
    
      
    const filteredProfileList = profileList.filter(element => {
      return filters.includes(element.staus);
    });
    
    console.log(filteredProfileList)

    【讨论】:

      猜你喜欢
      • 2016-12-26
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多