skip to Main Content
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

2

Answers


  1. You can use the ‘some’ method which iterates over the array and returns true as soon as the condition is met:

    let filtered = data.filter((item) => item.category_name.some((subItem) => subItem === category));
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search