How to filter a JS array with user defined number of filters?
Problem Description:
I have a Profiles array of objects that I would like to filter. The filter is a combination of Statuses in another array. The array of Statuses is defined by the user. The Profiles array can be filtered with one or more Statuses by the user. How can I write a filter function without knowing how many conditions should be checked in advance?
//the array to filter
let profileList = [{name: "John", staus: "green"}, {name: "Alex", staus: "yellow"}, {name: "Jane", staus: "green"}]
//user defined: they can add up to 30 statuses
let statusList = ["green", "yellow", "red", "black"]
//also user defined: they can filter by as many statuses as they want
let filters = ["green", "red"]
const filteredProfileList = profileList.filter(element => {
return //how to write the conditions with logical OR (||) if I don't know how many statuses will be used?
});
Solution – 1
You don’t need to know how many will be checked, you can just check if the array of filters includes the profiles status:
//the array to filter
let profileList = [{name: "John", staus: "green"}, {name: "Alex", staus: "yellow"}, {name: "Jane", staus: "green"}]
//user defined: they can add up to 30 statuses
let statusList = ["green", "yellow", "red", "black"]
//also user defined: they can filter by as many statuses as they want
let filters = ["green", "red"]
const filteredProfileList = profileList.filter(element => {
return filters.includes(element.staus);
});
console.log(filteredProfileList)