I am currently developing a project in Angular 9 using Typescript.
Within my project, I have both an array of strings and an array of a custom type.
My goal is to filter the array of custom types so that it only includes items whose property matches one of the strings in the string array. To illustrate, here is some code:
//Custom type declaration
export interface CustomType {
id: string;
name: string;
}
//Arrays initialization
customTypesArr: CustomType[] = [
{id: "000", name: "name 1"},
{id: "001", name: "name 2"},
{id: "002", name: "name 3"}
];
customTypesNamesArr: string[] = ["name 3", "name 1"];
The desired outcome is to create a new array from customTypesArr
that only contains items with a name property matching any string in customTypesNamesArr
. The resulting array should look like this:
myNewCustomTypesArr: CustomType[] = [
{id: "000", name: "name 1"},
{id: "002", name: "name 3"}
];
I've attempted to achieve this filtering using the following code snippet, but I'm having trouble getting it right:
customTypesArr.filter(item =>
customTypesNamesArr.forEach(name => {
if (name == item.name) {
return item;
}
})
);
I am uncertain whether using forEach()
is appropriate in this context...
If anyone could provide guidance or assistance on this matter, I would greatly appreciate it. Thank you.