I want to be able to filter on multiple strings(types) in an array. For example I want to filter on type meat and type fruit in the data-structure below. What I want to achieve is a filtered data object.
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"}]
Unfortunately it returns 4 results instead of the 2 as expected above.
I know how to deal with this in libraries like _underscore.js but I want to achieve it in modern EcmaScript.
Create an array of the type
s you want to include first, and then you can use an .includes
test on that array. (Currently, your post.type.includes(filter1, filter2)
doesn't work because includes
only accepts one argument)
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);
You could also use a Set
for less runtime complexity
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With