简体   繁体   English

按多个条件过滤数组

[英]Filter Array by Multiple Criteria

I'm looking to filter the following array:我正在寻找过滤以下数组:

const array = 
[{city: "Fullerton", techName: ["Sean"], routeName: ["Route 1"], routeDay: "Monday"},
{city: "Long Beach", techName: ["Sean", "Greg"], routeName: ["Route 1", "Route 3"], routeDay: "Monday"}, 
{city: "Huntington Beach", techName: ["Sean"], routeName: ["Route 1"], routeDay: "Monday"}];

With the following array:使用以下数组:

const filters = [{type: "routeDay", filter: "Monday"}, {type: "techName", filter: "Greg"}];

I am filtering a table with multiple filters and I cannot figure out how to filter by both filters.我正在过滤带有多个过滤器的表,但我无法弄清楚如何通过两个过滤器进行过滤。 I am able to filter by one or the other, but one one and the other.我可以通过一个或另一个过滤,但一个和另一个。

Any help is appreciated, thanks!!任何帮助表示赞赏,谢谢!!

You can filter the array, and for each item use Array.every() to iterate the array of filters , and check if the values are acceptable.您可以过滤数组,并为每个项目使用Array.every()迭代filters数组,并检查值是否可接受。

Get the relevant value by type from the current object.从当前对象中按type获取相关值。 If it's an array check if it contains the filter 's value.如果它是一个数组,检查它是否包含filter的值。 If not compare value and filter .如果不比较 value 和filter

 const array = [{city: "Fullerton", techName: ["Sean"], routeName: ["Route 1"], routeDay: "Monday"}, {city: "Long Beach", techName: ["Sean", "Greg"], routeName: ["Route 1", "Route 3"], routeDay: "Monday"}, {city: "Huntington Beach", techName: ["Sean"], routeName: ["Route 1"], routeDay: "Monday"}]; const filters = [{type: "routeDay", filter: "Monday"}, {type: "techName", filter: "Greg"}]; const result = array.filter(o => filters.every(({ type, filter }) => { const value = o[type]; return Array.isArray(value) ? value.includes(filter) : value === filter; })); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM