在数组上应用多个过滤器 [英] Applying multiple filters on an array

查看:76
本文介绍了在数组上应用多个过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,该项目有一个搜索页面,其中有一个基本的过滤器表单。我设法过滤数据,但一次只能过滤一个。我无法弄清楚应用多个过滤器以缩小数据范围的逻辑。

I have this project which has a search page where I have a basic filter form. I managed to filter the data but only with one filter at a time. I can't figure the logic behind applying multiple filters in order to narrow down the data.

示例:

let data = [{
    budget: "220",
    categories: ["party", "school"]
  },
  {
    budget: "450",
    categories: ["self"]
  },
  {
    budget: "600",
    categories: ["dev", "work"]
  }
];

const filters = {
  budget: ["200","500"],
  categories: ["party"]
}

//////Expected behavior:
Outputs only the first object because it's budget it's between 200 and 500 and it has "party" as it's category.

此示例基本上模拟了我的应用程序中的内容。如您所见,我有一个对象数组。每个对象都有一个预算和多个类别。
对于过滤器,假设我应用了预算过滤器(这将是范围过滤器)和一个类别过滤器。
如何将这些过滤器链接在一起以正确过滤数据?

This example simulates basically what I have in my app. As you can see, I have an array of objects. Each object has a budget and multiple categories. For the filters, let's say I apply a budget filter (which is going to be a range filter) and one category filter. How should I chain this filters together in order to filter the data properly?

推荐答案

每个过滤器都应具有一个功能可以处理支票。 filterHandlers 地图

Each filter should have a function that can handle the check. The filterHandlers is a Map of such handlers.

数组和过滤器对象传递给 applyFilters()。该方法获取过滤器的键(通过 Object.keys() ),并使用 Array.filters() 。使用 Array.every () 该项目由所有过滤器(使用相关处理程序)检查。如果所有检查都通过,则该项目将包含在结果数组中。

The array and the object of filters are passed to applyFilters(). The method gets the keys of the filters (via Object.keys()), and iterates the items with Array.filters(). Using Array.every() the item is checked by all filters (using the relevant handler). If all checks pass, the item will be included in the resulting array.

每当需要添加另一个过滤器时,都会向Map添加另一个处理程序。

Whenever you need to add another filter, you add another handler to the Map.

const filterHandlers = new Map([
  [
    'budget', 
    (val, [min, max]) => val >= min && val <= max
  ],
  [
    'categories', 
    (current, categories) => current.some( // some - at least one, every - all of them 
      (c) => categories.includes(c)
    )
  ],
  []
]);

const applyFilters = (arr, filters) => {
  const filterKeys = Object.keys(filters);
  
  return arr.filter(o => filterKeys.every((key) => {
    const handler = filterHandlers.get(key);
    
    return !handler || handler(o[key], filters[key]);
  }));
}

const data = [{"budget":"220","categories":["party","school"]},{"budget":"450","categories":["self"]},{"budget":"600","categories":["dev","work"]}];

const filters = {"budget":["200","500"],"categories":["party"]};

const result = applyFilters(data, filters);

console.log(result);

这篇关于在数组上应用多个过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆