What is the best way to extract items from another array that have approved IDs - is it through using map(), filter(),

I am unsure about the best approach to retrieve only the items (array with objects) that have been approved based on their id. Should I start by using map() and then filter(), or should I filter() them first and then map()?

export class AppComponent  {
  name = 'Angular';
  items = [
    { id: 535345, code: '432gdh4356' },
    { id: 634586, code: 'irdtry4567' },
    { id: 124315, code: 'fgdt43104f' },
    { id: 978767, code: 'eaw32134dd' }
  ];

  approvedId = [ 535345, 978767 ];

  ngOnInit() {
    this.getApprovedItems();
  }

  public getApprovedItems(): any {
    // result:
    // [{ id: 535345, code: '432gdh4356' }, { id: 978767, code: 'eaw32134dd' }]
  }
}

Answer №1

Consider implementing a filter mechanism:


 items = [
    { id: 235325, code: 'jgdnf3243' },
    { id: 654234, code: 'jdthr4567' },
    { id: 764532, code: 'hdkfj43104f' },
    { id: 978543, code: 'ieod32134dd' }
  ];

 approvedIds = [ 235325, 978543 ];

public getApprovedItemsList(): any {
  return this.items.filter(item => this.approvedIds.includes(item.id))
}

Answer №2

For filtering out items, you can utilize the filter() method.

Here's an example:

public getFilteredItems(): any[] {
  return this.items.filter(item => this.filteredIds.includes(item.id))
}

Answer №3

Please remember to implement Typing and utilize the output of your method.

export interface Code {
  id: number;
  codeValue: string;
}

export class MainComponent  {
  title = 'Angular';
  dataItems: Code[] = [
    { id: 321456, codeValue: '4gd34h56s' },
    { id: 672984, codeValue: 'iuhrt667' },
    { id: 843261, codeValue: 'gy6543tfg' },
    { id: 345679, codeValue: 'etwqwe23c' }
  ];
  authorizedItems: Code[];

  authorizedIds: number[] = [ 321456, 345679 ];

  initialize() {
    this.authorizedItems = this.getAuthorizedItems();
  }

  public getAuthorizedItems(): Code[] {
    return this.dataItems.filter((item: Code) => this.authorizedIds.includes(item.id));
  }
}

Answer №4

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

Answer №5

Here is a potential solution that might work out for you:

function fetchApprovedItems() {
    this.items.map((item) => {
        if(this.approvedIds.includes(item.id)){
            console.log(item);
            //{id: 535345, code: "432gdh4356"}
           // {id: 978767, code: "eaw32134dd"}
        }

    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize React to transform PDF files into PNG images and seamlessly upload them to Cloudinary

Currently, I am utilizing react typescript and looking to select a PDF file, transform the PDF into an image, and then upload the final image onto Cloudinary. Although I have a service set up for uploading images in my Cloudinary media library, I am unsu ...

Associate union with interface attributes

Can a union type be transformed into an interface in Typescript? My Desired Outcome If we have a union type A: type A = 'one' | 'two' | 'three'; I want to convert it to interface B: interface B { one: boolean; two ...

Master the Art of Scrolling Lists in Ionic 2

I am currently using Ionic2 for my project. One of the challenges I'm facing is scrolling to the top of a list when a specific event, called messageSend, occurs. Let me show you the code for this: <ion-content padding class="messages-page-conten ...

Using TypeScript along with the "this" parameter

Hi there, I'm encountering an issue with the code snippet below. It keeps throwing an error message that says "Property 'weatherData' does not exist on type 'XMLHttpRequest'." The purpose of this code is to display weather informat ...

Ways to compare values in an array and then add the array in PHP

Below you'll find the code I've been working on. I am attempting to create a graph using values from the following array: In the dates array, I have all 30 days listed. I also have arrays named pending_date and approved_date. My goal is to match ...

The variable 'cache' is not recognized by Angular

Everything runs smoothly on my local Angular app, but once deployed on Heroku using a Go server, I encounter issues with aot being disabled in the Angular build on Chrome and Opera, particularly on mobile devices using Linux and OSX. However, Safari presen ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...

Breaking down a large JSON array into smaller chunks and spreading them across multiple files using PHP pagination to manage the

Dealing with a large file containing over 45,000 arrays can be challenging, especially on a live server with high traffic. To address this issue, I used the array_chunk($array, 1000) function to divide the arrays into 46 files. Now, my goal is to access a ...

Retrieve all elements from an array that has been imported through the fs module

To extract the values from the array jsonParsed.students[actStudent].evnetsPartaken, which may look like [1,2,0] (note: check attachments for full data), I need a way to reference each value in correlation to the event number in the configEvents JSON array ...

Error message in VsCode plugin stating that property 'X' is not found on type '{}' within a Vue 3 template

Currently, I am in the process of setting up my vue-cli project that utilizes the composition API with <script setup> to fully integrate TypeScript. Each time I try to use variables within template tags, VSCode flags errors. I have already installed ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

What steps should I take to correctly identify the type in this specific situation?

Let's consider the function f, defined as follows: function f<T extends Fields = Fields>(props: Props<T>) { return null; } In this context, T represents a generic type that extends Fields. The concept of Fields is captured by the follow ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

What is the best way to set the text color of cell data in a mat-table to white for the entire row when the row is selected as

Is there a way to change the text color when a row is selected in my application? I have already figured out how to change the background color of the row, but how can I target the text within the cells? I'm considering using a similar approach to th ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Is it possible to retrieve the original array after removing filters in Angular?

Within my component, I have an array that I am filtering based on a search string. The filtering works as expected when the user inputs characters into the search field. However, I am encountering an issue when attempting to display all records again after ...

What is the best way to dynamically implement text ellipsis using CSS in conjunction with Angular 7?

i need to display a list of cards in a component, each card has a description coming from the server. In my component.html, I am using a ngFor like this: <div [style.background-image]="'url('+row.companyId?.coverUrl+')'" class="img- ...

"Implemented a fresh pathway within the app-routing.module.ts file, but unfortunately, ngxAdmin is experiencing functionality issues

While customizing the ngx-admin template, I attempted to incorporate a new module into the app module and added its route in app-routing.module.ts. However, upon trying to open it, the module seems to be stuck at loading without any errors appearing in the ...

Utilizing mapped types in a proxy solution

As I was going through the TS Handbook, I stumbled upon mapped types where there's a code snippet demonstrating how to wrap an object property into a proxy. type Proxy<T> = { get(): T; set(value: T): void; } type Proxify<T> = { ...

Obtain canvas context within Angular from within a Web Worker

I am currently using platformWorkerAppDynamic to showcase my Angular application, but I am facing a challenge when trying to manipulate the canvas context. Though I can create a canvas using Renderer2, I am struggling to find a way to call the getContext(& ...