I am working with an array of objects:
let response = [{"id": 1, "name": "Alise", "price": 400, "category": 4}];
In addition to the array of objects, I have some arrays that will be used for filtering:
let names = ["Jessy", "Megan"];
let prices = [300, 500];
let category = [1,2,4];
My goal is to filter the array using these filtering arrays with a condition of AND between names, prices, category
, and an OR condition between elements in each array: Jessy
OR Megan
.etc
To tackle this issue, I came up with the following solution:
const filterByCategory = (response: IResponse[], filterBy: any[]) => response.filter((e: IResponse) => filterBy.indexOf(e.category) > -1);
const filterByPrice = (response: IResponse[], filterBy: any[]) => response.filter((e: IResponse) => e.price in filterBy);
Now, I'm unsure about how to make the call more efficient:
First approach:
filter() {
let filtered = filterByCategory(response, category);
filtered = filterByPrice(filtered, prices);
}
Second approach:
filter() {
let filtered = [];
if (category && category.length) {
filtered = filterByCategory(response, category);
}
if (prices && prices.length) {
filtered = filterByCategory(filtered, category);
}
}
Third approach:
let filtered = response.filter((element) => {
return category && category.indexOf(e.category) > -1 &&
prices && prices.indexOf(e.price) > -1 && etc.
});
- The first approach allows for easy modification of the filtering logic without changing the main filter.
- The second approach is similar to the first but includes additional checks.
- The third approach is the shortest, but may be difficult to modify in the future.