I believe it would benefit us all to enhance the educational value of our responses. While the filtered answer is effective, we should delve deeper into why it works and why the original poster is considering using map().
My approach to this query:
There is actually no need to utilize map() in this scenario. The map() method typically applies a function to each item in a list. One might assume that applying a filter-function to each item makes sense, which is true! However, this is precisely what the filter() method accomplishes. Similar to map(), filter() implements a function on every element in an array. Nevertheless, filter() requires a function that returns a boolean value (true/false). If the result is true, filter() will include the element in the resulting array; otherwise, it won't. Hence, in this context, only filter() is necessary.
The following code segment draws inspiration from MoxxiManagarm's response, with additional comments included:
export interface Code {
id: number;
code: string;
}
export class AppComponent {
name = 'Angular';
items: Code[] = [
{ id: 535345, code: '432gdh4356' },
{ id: 634586, code: 'irdtry4567' },
{ id: 124315, code: 'fgdt43104f' },
{ id: 978767, code: 'eaw32134dd' }
];
approvedItems: Code[];
approvedId: number[] = [ 535345, 978767 ];
ngOnInit() {
this.approvedItems = this.getApprovedItems();
}
public getApprovedItems(): Code[] {
return this.items.filter((item: Code) => this.approvedId.includes(item.id));
}
}