简体   繁体   中英

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.

Get the relevant value by type from the current object. If it's an array check if it contains the filter 's value. If not compare value and 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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