How can I filter based on multiple values in Javascript.
I want to make a frontend filter in react where all value is a select field except name its a search Input.
const data = [
{
name: "anna",
group: "group 1",
house: "green",
subject: "math"
},
{
name: "mike",
group: "group 2",
house: "blue",
subject: "science"
},
{
name: "mike",
group: "group 2",
house: "blue",
subject: "physics"
},
{
name: "holly",
group: "group 1",
house: "green",
subject: "chemistry"
}
]
Expectation:
- selecting "group 1" and "green" should result in
[
{
name: "anna",
group: "group 1",
house: "green",
subject: "math"
},
{
name: "holly",
group: "group 1",
house: "green",
subject: "chemistry"
}
]
- selecting "mike", "group 2" and "blue" should result in
[
{
name: "mike",
group: "group 2",
house: "blue",
subject: "science"
},
{
name: "mike",
group: "group 2",
house: "blue",
subject: "physics"
}
]
- Selecting nothing should render whole array
Thank you.
CodePudding user response:
You can do like this
data.filter(x=>x.group=='group 1'&& x.house=="green")
var data = [
{
name: "anna",
group: "group 1",
house: "green",
subject: "math"
},
{
name: "mike",
group: "group 2",
house: "blue",
subject: "science"
},
{
name: "mike",
group: "group 2",
house: "blue",
subject: "physics"
},
{
name: "holly",
group: "group 1",
house: "green",
subject: "chemistry"
}
]
var result = data.filter(x=>x.group=='group 1'&& x.house=="green")
console.log(result)
CodePudding user response:
const data = [
{
name: "anna",
group: "group 1",
house: "green",
subject: "math"
},
{
name: "mike",
group: "group 2",
house: "blue",
subject: "science"
},
{
name: "mike",
group: "group 2",
house: "blue",
subject: "physics"
},
{
name: "holly",
group: "group 1",
house: "green",
subject: "chemistry"
}
];
function filterArr(v1='', v2='', v3='', v4=''){
return data.filter(f=>{
return (f.name).includes(v1) && (f.group).includes(v2) && (f.house).includes(v3) && (f.subject).includes(v4);
});
}
let arr = filterArr('mike', 'group 2');
console.log(arr);