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);