Filtering with multiple options in React Redux:
filterOption:
{
option1: ['GY'],
option2: ['Y'],
option3: [],
option4: ['N'],
option5: ['A', 'W'],
}
The filter function:
body.search.listFiltered = body.search.list.filter(
(i) =>
filterOption["option1"].includes(i.s) &&
filterOption["option2"].includes(i.b) &&
filterOption["option3"].includes(i.u.p) &&
filterOption["option4"].includes(i.f.p) &&
filterOption["option5"].includes(i.n.p)
);
It should work even when for example option3 is empty—it could be any other option for that matter.
Each option-x works with a particular object, such as option1 with object i.s. While option2 with i.b and so forth...
Right now it's returning an empty array [].
What am I doing wrong here?
You can do something like this
const filterOption = {
option1: ['GY'],
option2: [true],
option3: [],
option4: [false],
option5: ['A', 'W']
}
const array = [{b:'GY'},{s:true},{p:'A'},{x:false},{e:'A'}, {b:'GY',s:true,p:'A', x:false, e:'A' }]
const result = array.filter(
(i) =>
{
const filterCheck = option => item => filterOption[option].length > 0 ? filterOption[option].includes(item) : true
return filterCheck("option1")(i.b) &&
filterCheck("option2")(i.s) &&
filterCheck("option3")(i.p) &&
filterCheck("option4")(i.x) &&
filterCheck("option5")(i.e)}
)
console.log(result)