In one of my projects, I ran into the following problem. There was an array of objects and I had many filter conditions, stored in another array. These filters were generated by the user in the web app, using multiple checkboxes.
In this short post, I'd like to show you how to use Array.prototype.filter
method in case you need to use multiple filter conditions.
Let's start with this simplified set of data:
const users = [
{
id: 1,
status: "normal",
country: "japan",
},
{
id: 2,
status: "premium",
country: "italy",
},
{
id: 3,
status: "premium",
country: "japan"
},
{
id: 4,
status: "normal",
country: "sweden"
},
{
id: 5,
status: "normal",
country: "germany"
},
{
id: 6,
status: "normal",
country: "italy"
},
{
id: 7,
status: "gold",
country: "sweden"
},
{
id: 8,
status: "gold",
country: "germany"
}
];
If we want to filter this collection in a dynamic way, the good option might be to store our filters in another array:
const filters = [{ type: "status", name: "gold" }, { type: "country", name: "sweden" }];
Here I'm creating an array of objects, and each object represents a separate filter. There might be dozens of properties for each user
so the filters
array is created dynamically.
To filter such collection we need to merge the filter
and some
Array methods. Here we want to find all elements that have status
equal to 'gold' or country
equal 'sweden'.
const filteredResults = users.filter(el => filters.some(filterEl => el[filterEl.type] === filterEl.name));
/*
Result:
[
{
"id": 4,
"status": "normal",
"country": "sweden"
},
{
"id": 7,
"status": "gold",
"country": "sweden"
},
{
"id": 8,
"status": "gold",
"country": "germany"
}
]
*/
This is a simple example but most of our solutions will start from this point. Using filter
, some
, every
, and other Array methods together will solve most of your problems.
Top comments (1)
nice post.