'Multiple filters in javascript
I'm trying to do a multiple filter in javascript. It consists in 5 filters: search input, maxYear, minYear and if a string contains one item of an array of strings (x2).
I started doing this:
let entries = formattedJsonResults;
if (search) {
const filtered = entries.filter(entry =>
entry.title.toLowerCase().includes(search.toLowerCase())
);
entries = filtered;
} else if (minYear) {
const filtered = entries.filter(entry =>
Number(entry.date.slice(0, 4)) >= minYear.getFullYear()
);
entries = filtered;
} else if (maxYear) {
const filtered = entries.filter(entry =>
Number(entry.date.slice(0, 4)) <= maxYear.getFullYear()
);
entries = filtered;
}
But later I realized that they are not compatible. Eg, if search exists, I'll never access to the minYear filter.
Can someone help me please? thanks
Solution 1:[1]
Use individual if-statements, rather than an if-else. Also, use the previously filtered result for the next filter.
const entries = formattedJsonResults;
let filtered = entries;
// Filter by search term
if (search) {
filtered = filtered.filter(entry =>
entry.title.toLowerCase().includes(search.toLowerCase())
);
}
// Filter by minimum year
if (minYear) {
filtered = filtered.filter(entry =>
Number(entry.date.slice(0, 4)) >= minYear.getFullYear()
);
}
// Filter by maximum year
if (maxYear) {
filtered = filtered.filter(entry =>
Number(entry.date.slice(0, 4)) <= maxYear.getFullYear()
);
}
// Filter by annotations
if (annotations) {
filtered = filtered.filter(entry =>
annotations.includes(entry.annotation)
);
}
console.log(filtered); // After filtering 1x to 4x
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
