Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Filter on multiple strings in JS? [duplicate]

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.

like image 947
WDP Avatar asked Jan 02 '23 17:01

WDP


1 Answers

Create an array of the types 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);
like image 197
CertainPerformance Avatar answered Jan 13 '23 13:01

CertainPerformance