如何在JS实现多串过滤?
我希望能够在一个数组中的多个字符串(类型)上过滤。例如,我想在过滤下面的数据结构中键入肉类和水果。 我要实现的是经过筛选的数据对象。
const data = [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}, {type:"fish", food: "red snapper"}, {type:"vegetables", food:"fungi"}]
let filter1 = 'meat'
let filter2 = 'fruit'
const filteredData = data.filter( post => post.type.includes(filter1, filter2) ? post:'');
// My expected result after filtering: [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}]
很遗憾,它返回%4个结果,而不是上面预期的%2。
我知道如何在_underscore.js这样的库中处理此问题,但我希望在现代ECMAScript中实现它。
解决方案
创建要首先包括的type
数组,然后可以对该数组使用.includes
测试。(当前,您的post.type.includes(filter1, filter2)
不起作用,因为includes
只接受一个参数)
const data = [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}, {type:"fish", food: "red snapper"}, {type:"vegetables", food:"fungi"}]
let filter1 = 'meat'
let filter2 = 'fruit'
const filters = [filter1, filter2];
const filteredData = data.filter(({ type }) => filters.includes(type));
console.log(filteredData);
您还可以使用Set
来降低运行时复杂性
const data = [{type: "meat", food: "hamburger"}, {type:"fruit", food:"banana"}, {type:"fish", food: "red snapper"}, {type:"vegetables", food:"fungi"}]
let filter1 = 'meat'
let filter2 = 'fruit'
const filters = new Set([filter1, filter2]);
const filteredData = data.filter(({ type }) => filters.has(type));
console.log(filteredData);
相关文章