I have an array of objects which I need to filter.
If the object has an active value of true then it should always be returned regardless of other factors.
If searchText is entered then the rest of the list should be filtered by this search text.
If a countrySearch is entered then the list should be filtered by this value, and also by the searchText if that is provided.
const searchText = 'Di';
const countrySearch = "USA";
const myArray = [
{
name: "Tom",
country: "UK",
active: true
},
{
name: "Dick",
country: "USA",
active: false
},
{
name: "Dimmon",
country: "FR",
active: false
}
].filter(item => {
if (item.active === true) {
return true;
}
if (searchText) {
if(item.name.includes(searchText)) {
return true;
}
}
});
console.log(myArray);
In this example the new array should contain Tom as active is true. It should contain Dick as he passes both the searchText and countrySearch test. Dimmon should not be in the new array as he passes only 1 of the searchText and countrySearch search conditions.
It is possible for me to solve this using my current approach but its getting messy with nested if statements. Also my search conditions are likely to grow in complexity overtime. Is this a good case for functional programming?
ifstatements, you could use||and&&..filter( item => item.active || item.name.includes(searctText) )