Reputation: 523
Hello I wish to filter array of object based on my state, I have several properties in my filters object and I wish to return array which fill these requirements. So far I managed to do it on only one condition. I know why, it is because of my ifs but I don't really know how to code it to apply to all conditons like for example in case of false in danger and services, I wish only to return object which type is relax
const markers = [{
name: "one",
type: "danger"
},
{
name: "two",
type: "relax"
},
{
name: "three",
type: "service"
},
{
name: "four",
type: "danger"
},
]
const [filters, setFilters] = useState({
danger: true,
relax: true,
services: true,
});
const filtered = markers((el) => {
if (!filters.danger) return el.type !== "danger";
if (!filters.relax) return el.type !== "relax";
if (!filters.services) return el.type !== "services";
return el;
});
in Case of danger and services set to false, I wish to have output
const markers = [
{name: "two", type:"relax"},
]
Upvotes: 0
Views: 54
Reputation: 2549
You can achieve this by using filter method.
const markers = [
{name: "one", type:"danger"},
{name: "two", type:"relax"},
{name: "three", type:"service"},
{name: "four", type:"danger"}
];
// Filter your data as you wish
const filtered = markers.filter(item => {
if(item.type == "relax") return true;
if(item.type == "service") return true;
});
console.log(filtered);
Filter wrapper
const markers = [
{name: "one", type:"danger"},
{name: "two", type:"relax"},
{name: "three", type:"service"},
{name: "four", type:"danger"}
];
// Create wrapper function
// to pass parameters to filter
const fltr = (array, types) => array.filter(item => types.indexOf(item.type) > -1);
// Test 1
console.log(fltr(markers, ["danger"]));
// Test 2
console.log(fltr(markers, ["relax", "service"]));
Upvotes: 0
Reputation: 8581
You can do it with a quick filter() function:
const markers = [{
name: "one",
type: "danger"
},
{
name: "two",
type: "relax"
},
{
name: "three",
type: "service"
},
{
name: "four",
type: "danger"
},
];
const filters = {
danger: false,
relax: false,
service: true,
};
const shouldIncludeMarker = ({type}) => filters[type];
console.log(markers.filter(shouldIncludeMarker));
Upvotes: 1