Filter array of objects in Angular4 without using any built-in pipe functions

I am working with an array of links where each element is an object containing a link, description, and category. I have different components to display these links, and I want each component to only display links from its specific category. So, I need to filter the array based on category.

I currently have a mock-up array that stores all the links.

I am attempting to filter the array of objects without using a pipe. The reason for this decision can be found here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

According to the Angular team's recommendation, it is better to handle filtering and sorting logic in the component itself rather than using a pipe:

@Component({
    selector: 'startups',
    templateUrl: './startups.component.html'
})

export class StartupsComponent implements OnInit {

constructor(private appLinksService: DigitalCoinHubService) { }

title = 'Startups';


links: DCHlinks[]; 

startupsLinks: DCHlinks [] = []; 


getLinks(): void {
  this.links = this.appLinksService.getLinks(); 

  for (let i in this.links)
  {
     if (this.links[i].dchCategory == 'startups' )
     {
         this.startupsLinks.push(this.links[i]);
     }

  }

}

ngOnInit() {
    this.getLinks();   

}

}

Firstly, I retrieve the main array from the service:

this.links = this.appLinksService.getLinks();

Next, I attempt to create a new array that will only contain relevant links based on category. However, when trying to populate this new array using push method, I encounter an error:

Error: Property 'push' does not exist on type 'DCHlinks'.

The class definition for DCHlinks is as follows:

export class DCHlinks {
   dchLink: string;
   dchLinkTitle: string;
   dchLinkDescription: string;
   dchCategory: string;
 }

Any suggestions on how to implement this simple filter without using a pipe?

Thank you!

Answer №1

Make sure to initialize the array just like you did for startupsLinks

links: DCHlinks[] = [];

Alternatively, you can utilize array.filter method to extract the relevant information

this.startupsLinks = this.links.filter(item=>item.dchCategory == 'startups');

Answer №2

I encountered a similar issue, but I tackled it in a different manner. I had an Array of objects and wanted to implement filtering using an HTML select option. This involved providing the data that would filter the array of objects.

`$

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    heroes = [{
        name: "shubh",
        franchise: "eng"
      },
      {
        name: "Ironman",
        franchise: "Marvel"
      },
      // More object entries here...
    ];
    
    // The crucial part is in the filter section. I faced numerous challenges as this didn't work unless this particular line was included. The filter method only functioned once.
    newarr = this.heroes;

    // Therefore, I created a new array to store the old array value every time. We then replaced the value in the filter function.
    filter(heroes: string) {
      console.log(heroes);
      this.heroes = this.newarr; // Replace the value and save the old value
      let heroesnew = this.heroes.filter((data => data.name == heroes));

      this.heroes = heroesnew;
      console.log(this.heroes);

    }
    <!––"#sel" is the template variable fetching the value property data from the option field ––>
    <select #sel class="custom-select custom-select-sm" (change)="filter(sel.value)">
      <option>All</option>
      <option value="Batman">Batman</option>
      <option value="Superman">Superman</option>
      <option value="satman">Satman</option>
      // Other options listed here...
    </select>

    <!–– This is the table that needs to be filtered ––>
   <div>
      <table class="table table-hover ">
        <thead class="thead-dark">
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>Franchise</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let incidence of heroes">
            <td>{{ incidence.name}}</td>
            <td> {{ incidence.franchise }}</td>
          </tr>
        </tbody>
      </table>
    </div>

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

Unraveling the Structure of an Angular2 Project

Upon reviewing a downloaded typescript/Angular2 project structure that serves as the base code for extension, I find myself a bit puzzled. The confusion lies in how providers are initialized and provided in Angular 2. The current code snippet from the Ap ...

Using a foreach loop to showcase information within elements, specifically for JSON with several arrays

I am working with JSON data from an external domain to create a list of posts by extracting and displaying the necessary information. { "dati": [ { "id": 98762, "tipo": "eventi", "titolo": “TITOLO ...

What is preventing Angular from functioning as the default folder homepage in Outlook 2013?

Trying to replicate the functionality of the Outlook Kanban board using Angular has been a bit challenging for me. I managed to create the application successfully and made it work in IE11. However, when I set it as the homepage for my task folder in Outlo ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

When utilizing Ionic Firebase, the user profile saved in the sidemenu is stored using the Events class. However, the saved profile disappears as soon as

Hello there. I am currently working on displaying my user's information in the sidemenu, and after some research, I found that using the Events class might solve this issue. However, I have noticed that the data saved in subscribe gets destroyed whene ...

Filtering a table based on a specified letter - the ultimate guide!

I would like to create a table with the ability to filter data by letters. For example, if 'A' is clicked, only data that begins with 'A' should be shown in the table. How can I achieve this? I have already set up a table with hardcode ...

Angular with Entypo Icons

If you want to use the Entypo SVG icon set in your Angular application, you will need to add some JavaScript to the page. Here is an example of how you can do this: const entypo = require('entypo') document.body.insertBefore(entypo.getNode(), d ...

Unable to reach the array file

Having trouble accessing the elements of the file array const p_page = postP.new_pages; const p_page_o = postP.new_pages_order; const p_page_o_len = p_page_o.length; if (p_page_o_len > 0) { for (let i = 0; i < p_page_o_len; i++) { c ...

In Angular, there is an issue where the @ViewChild decorator does not reflect changes when the value of the child component is updated within the

Does anyone know why the console.log("My status :", status); is not displaying after the child property has changed? Here is my child component code: @Output() public isLoggedIn: Subject<boolean> = new Subject(); constructor( private auth ...

Issues arise in Ionic 3 when attempting to use scripts or external custom jQuery plugins within inner pages

When I utilize a script tag in my index.HTML file, it functions properly on the initial or root pages of Ionic 3. However, upon navigating to other pages using NavController, the script ceases to work on these inner pages. How can I implement a custom jQ ...

Memory Leak in Char Array

I'm currently facing difficulties in properly releasing the memory allocated for my char* array. In the code snippet provided below, I initialize a char* array called input which stores pointers to individual words along with a terminating pointer NUL ...

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

A guide to effectively utilizing a TypeScript cast in JSX/TSX components

When trying to cast TypeScript in a .tsx file, the compiler automatically interprets it as JSX. For example: (<HtmlInputElement> event.target).value You will receive an error message stating that: JSX element type 'HtmlInputElement' is ...

Can you explain the variance between the (Record<string, unknown>) and object type?

Can you explain the distinction between type Record<string, unkown> and type object? Create a generic DeepReadonly<T> which ensures that every parameter of an object - and its nested objects recursively - is readonly. Here's the type I c ...

Incorporating two components and nesting one within the other, similar to the way angular-material seamlessly integrates its components

I recently discovered the angular-material module and I'm a bit perplexed about how it allows multiple components to be used inside one another in the same place. Take a look at the example below: <mat-drawer-container class="example-container"> ...

Populating a 2D array in C twice - initially with a single number at random positions, followed by filling the remaining slots with random numbers

I'm feeling really stuck right now. I'm new to programming in C and currently trying to grasp the concept of 2D arrays. My assignment involves creating an array and randomly assigning -1 to some positions, then filling the rest with random number ...

Using Angular with Bootstrap to implement a typeahead feature

I've been working on getting my Typeahead feature to function properly: <div *ngFor="let item of items; index as i"> <input type="text" name="name{{i}}" [(ngModel)]="item.name" [ngbTypeahead]="searchItem" /> </div> Within the c ...

Angular Kendo UI File Uploader

I faced a challenge with the Kendo Ui Angular's kendo-upload component. I needed to provide [saveUrl] and [removeUrl] in the kendo-upload, but since I split the project into service and component parts, I opted to handle the Upload logic myself within ...

RXJS expand keeps on recursing indefinitely

After successfully uploading a file to Firebase, I implemented a recursive function to listen for GCP trigger logs. Everything seems to be working well, but I'm facing an issue where the recursive expand function never exits. Despite checking the val ...

Unable to create a line break within an ion-item

I'm facing a bit of a dilemma with this straightforward issue. Can't seem to find a solution. The following code is not producing the desired outcome: <div text-wrap ion-item no-lines> "No result found. <br/> Please ent ...