Skip to content
Advertisement

How to compare an array of objects with an array of strings?

How to compare these arrays? I want to compare and get a result like the below.

Array of string

 ["Typo", "Buttons"]

Array of object

[
  {icon: "General", categoryName: "Buttons"}
  {icon: "DataDisplay", categoryName: "Typo"}
  {icon: "Other", categoryName: "Sliders"}
]

As you can see there is no Sliders categoryName in the array of string. I expected the result should be another array of objects. As the following

[
  {icon: "General", categoryName: "Buttons"}
  {icon: "DataDisplay", categoryName: "Typo"}
]

Thanks!

Advertisement

Answer

You can use .filter as follows:

const categories = ["Typo", "Buttons"]
const items = [
  {icon: "General", categoryName: "Buttons"},
  {icon: "DataDisplay", categoryName: "Typo"},
  {icon: "Other", categoryName: "Sliders"}
]

const res = items.filter(item => categories.includes(item.categoryName));

console.log(res);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement