How to compare these arrays? I want to compare and get a result like the below.
Array of string
JavaScript
x
2
1
["Typo", "Buttons"]
2
Array of object
JavaScript
1
6
1
[
2
{icon: "General", categoryName: "Buttons"}
3
{icon: "DataDisplay", categoryName: "Typo"}
4
{icon: "Other", categoryName: "Sliders"}
5
]
6
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
JavaScript
1
5
1
[
2
{icon: "General", categoryName: "Buttons"}
3
{icon: "DataDisplay", categoryName: "Typo"}
4
]
5
Thanks!
Advertisement
Answer
You can use .filter
as follows:
JavaScript
1
10
10
1
const categories = ["Typo", "Buttons"]
2
const items = [
3
{icon: "General", categoryName: "Buttons"},
4
{icon: "DataDisplay", categoryName: "Typo"},
5
{icon: "Other", categoryName: "Sliders"}
6
]
7
8
const res = items.filter(item => categories.includes(item.categoryName));
9
10
console.log(res);