Comparing string to array – React

let category = "design" //This place is changing, like art, design, photo

let filtered = data.filter((item) => category === item.category_name)`

category contains a string. item.category_name is an array.

What I want to do is a filtering event. but an item can have multiple categories.

For example, the category of the 3rd item is as follows :

"category_name" : [ "design", "art" ],

How can I get the 3rd item to be selected when the category variable is art or design?

how can i compare array with a string

>Solution :

You can use the include method, it works for strings and arrays.

let filtered = data.filter((item) => item.category_name.includes(category))

so "design".includes("design") and ["design", "art"].includes("design") will both return true

However, it would be best if you turned item.categoryName into an array, for consistency. Items with one category could have an array with only one item.

Leave a Reply