Reputation: 3
How to filter conditionally multiple field in Javascript.
Hi, i want to filter some data in javascript using filter, but in this case i want to accept to values, basicly what i'm trying todo is i want to create some search input then return the data, but i also want when the user type category
in search input the result also show the category
const items = [
{ name: "Magazine", category: "Book"},
{ name: "Marker", category: "Pen"},
{ name: "Litelature", category: "Book"},
{ name: "Comics", category: "Book"},
{ name: "Drawer", category: "Pen"}
]
here i already implement the search filter.
const input = "Pen"
const filtered = items.filter((item) =>
item.name.toLowerCase().includes(input.toLowerCase())
)
as you can see that code return nothing since only filtering the name field. how can i implement filter also to the category field
Upvotes: 0
Views: 69
Reputation: 123397
Use an or
condition, like
const input = "Pen"
const filtered = items.filter((item) =>
item.name.toLowerCase().includes(input.toLowerCase()) ||
item.category.toLowerCase().includes(input.toLowerCase())
)
Upvotes: 2