Targeted filtering for specific values

I need assistance with filtering the value of PLAN

https://i.sstatic.net/QZEqu.png

When I input a value like 1

https://i.sstatic.net/N1SCz.png

The filter works correctly...

However, if I input the value 4, I encounter an issue...

https://i.sstatic.net/54WNB.png

I also retrieve information for place 8.

I'm having trouble understanding what's causing this problem?

Thank you in advance for helping me solve this issue.

todo.service.ts file

PLN_PLC = [
    {
      PLACECODE: 26,
      PLACELABEL: "Fundsettle",
      PLN_SVM: [
        {
          SVM: 16111801,
          ISIN: "LU0100749679",
          LABEL: "NEKR FD LIFESTYLE DYNAMICC",
          PLN: [
            {
              CODE: "NEKR01",
              PLAN: 8,
              CANAL: "*",
              AV: "A",
              LIB: "Fonds NEKRenta 8",
              DATEV_EFFECTIVE: "0001-01-01",
              PLAGE: [
                {
                  BORNE: 9999999999999.99,
                  FRAIS_BORDEREAU: 0.00,
                  FRAIS_RETRAIT: 0.00,
                  TYPE_COURTAGE: 1,
                  COURTAGE: 0.00,
                  MIN_COURTAGE: 0.00,
                  TYPE_FRAIS_ETR: 1,
                  FRAIS_ETRANGERS: 2.00,
                  MIN_FRAIS_ETR: 0.00
                },
                // Other data...
              ]
            },
            // Other data...
          ]
        },
        // Other data...
      ]
    },
    // Additional data...
];

// Code continues...

todo.component.ts

// TypeScript code for filtering by plan

export class TodoComponent implements OnInit {
  tarificationTitre: PlnPlcInfo[] = [];

  planFilter: string = '';

  constructor(private todoService: TodoService) { }

  ngOnInit() {
    this.tarificationTitre = this.todoService.PLN_PLC;
  }

  filterByPlan() {
    this.tarificationTitre = this.todoService.PLN_PLC.filter(item => {
      return item.PLN_SVM.some(svm => svm.PLN.some(plan => plan.PLAN.toString() === this.planFilter));
    });
  }

}

tarification-titre.response.ts

// Definition of interfaces used in the response

export interface TarificationTitreResponse {
  PLN_PLC: PlnPlcInfo[];
}

export interface PlnPlcInfo {
  PLACECODE: number;
  PLACELABEL: string;
  PLN_SVM: PlnSvmInfo[];
}

// More interfaces defined...

todo.component.html

<div class="container text-center">
    <h2 class="pt-3 pb-3">HTML Table</h2>

    <div class="row justify-content-center">

        <div class="col-12 col-sm-6 col-md-4">
            <div class="mb-2 d-flex align-items-center">
                <!-- Plan input field -->
                <label for="plan" class="mr-2" style="margin-right: 4px;">Plan</label>
                <input type="text" id="plan" name="plan" class="form-control w-60" [(ngModel)]="planFilter" (ngModelChange)="filterByPlan()" placeholder="Filter by PLAN">
            </div>
        </div>

    </div>

    <table class="mb-5">
        <tr>
            <th>Client Rate 1</th>
            <th>SVM</th>
            <th>ISIN</th>
            <th>Name</th>
            <th>Place</th>
        </tr>
        
        // HTML table content rendering...
        
    </table>
</div>

Answer №1

Filtering based on PLN_PLC occurs when certain elements meet the specified condition

PLN_PLC.filter(item => item.PLN_SVM.some(svm => svm.PLN.some(plan => plan.PLAN === 8)))

It appears that multiple filters are needed

PLN_PLC.filter(item => item.PLN_SVM.some(svm => 
                                svm.PLN.some(plan => plan.PLAN === 8)))
       .at(0) // equivalent to your svmInfo.PLN[0]
       .PLN_SVM.filter(plnSvm => plnSvm.PLN.some(plan => plan.PLAN === 8)

The final output is as follows :

[
  {
    "SVM": 16111801,
    "ISIN": "LU0100749679",
    "LABEL": "NEKR FD LIFESTYLE DYNAMICC"
    ...
    }
  },
  {
    "SVM": 37906990
    ...
  }
]

Answer №3

There seems to be an issue within this section of the code:

PLN_PLC.filter((item) =>
  item.PLN_SVM.some((svm) =>
    svm.PLN.some((plan) => plan.PLAN.toString() === this.planFilter)
  )
);

If there is a PLN field containing at least one object with its PLAN value matching the planFilter, then svm.PLN.some will return true. Consequently, item.PLN_SVM.some will also return true, resulting in the entire element within the PLN_SVM array being returned.

Please take into account the following example:

const PLN_PLC = [
  {
    PLN_SVM: [{ PLN: [{ PLAN: 8 }, { PLAN: 4 }] }]
  },
...
]

The output generated by the filterByPlan function will contain the first object (

PLN_SVM: [{ PLN: [{ PLAN: 8 }, { PLAN: 4 }] }]
), which includes an internal object with a PLAN field set to 4, which is not the intended result.

To address this, you can store the desired plans in an array like so:

function filterByPlanNew(array) {
  const result = [];

  array.forEach((item) => {
    item.PLN_SVM.forEach((svm) => {
      svm.PLN.forEach((plan) => {
        if (plan.PLAN === 8) {
          result.push(plan);
        }
      });
    });
  });

  return result;
}

Alternatively, you could flatten your data structure...

Visit codesandbox.

Edit:

If you wish to retain the same data structure as what filterByPlan provides, refer to this codesandbox.

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

How can RootStateOrAny be turned off in React with typescript?

Whenever I need to employ useSelector, I find myself repeating this pattern: const isLoading = useSelector( (state) => state.utils.isLoading ); Is there a shortcut to avoid typing out RootStateOrAny each time? It's starting to become a hassl ...

The formatting for Angular material radio buttons is malfunctioning

My attempt to include a mat-radio-button in my code is encountering issues. The styles are not applying correctly, despite not having any custom classes or style overrides for the radio buttons. The fill element is off-center and lacks the Angular Material ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

Using setTimeout within a for loop to dispatch notifications

I'm facing an issue with sending notifications based on certain parameters. I attempted to use a combination of for loop and setTimeout in my code, but all the notifications are sent simultaneously instead of at timed intervals. The relevant snippet l ...

Using Angular: Passing a service as a parameter

I have a desire to improve the organization of my code by moving certain functions into an external file and accessing them from multiple components. These functions rely on a service: The MyFunctions Class import { Service1 } from "../_services&quo ...

Submit Angular form with only the updated field values, not the entire form data

Upon submitting my Angular form, I noticed that only the values for the changed fields are being captured. Is this behavior correct, or should I be getting the full form values instead? // Profile.html <form [formGroup]="profileForm" (ngSubmit)="submit ...

Angular 2 seems to be overwhelmed with loading files when refreshed

Update 2 It appears that there is a bug in my Angular 2 application. You can view the issue here: https://github.com/angular/angular/issues/9359 Whenever I refresh the page, my very simple Angular 2 application loads hundreds of JS/HTML/CSS files. Is the ...

Nrwl NX encountering JavaScript heap exhaustion during linting process

Currently, I am delving into an Nx monorepo that houses numerous Angular 15 applications and some shared libraries. When I utilized the nx cli to create a new Angular application, everything went smoothly - serving and building the application posed no iss ...

Crop the contents of an array between two specified characters

Looking to extract individual values from an array like this: "Names": [ "Name[name]", "Result[Type]", "Validation[Option]", "Status[Pointer]" ] The desired output should be: "Names": [ "name", "Type", "Option", ...

Using Angular, you can easily add a <div> dynamically to all elements that share a class

In order to implement a solution, I am tasked with adding a new div element with the class '.cart-list-value .delete-product', which will contain a background image, to all elements that have the class .cart-list-item. Although I successfully man ...

Angular ng2-chart: i would like to showcase both the actual value and a corresponding percentage value, sourced from a different location but sharing the same index

I have incorporated an angular doughnut chart from ng2-chart and I am currently working on customizing the tooltip. In my scenario, in addition to displaying the tooltip label and value, there is another value - a percentage. While the doughnut chart displ ...

`A constant stream of observations being triggered`

In my application, there is a specific page that retrieves and displays the members. The API response includes pagination information, and only 5 users are shown on the page at a time. Below is the method within the member.service that handles member retri ...

Leveraging TypeScript modules without the need for require()

I created a TypeScript 2.3 app called app.ts that requires the Vue.js library version 2. I manually added the Vue.js script src in the HTML file. All I wanted was to use Vue.js with type checking. I thought I could simply reference it like this: /// & ...

What is a quick way to assign object properties to another object in TypeScript?

Sample: response.rooms.push({ maxPlayers: doc.maxPlayers, ownderId: doc.ownderId, roomId: doc.ownderId, state: doc.state, type: doc.type, }); All the parameters share the same name here. However, the doc object has additional parameters that I d ...

Guide to Generating a Library Using Angular-CLI

Can someone guide me on creating a custom Angular library using angular-cli and publishing it to the npm repository? I need to include other external libraries and expose my module along with some services in the index.ts file. Could you please provide s ...

What is the best way to employ TypeScript for passing parameters to JavaScript functions that utilize the arguments object?

Using Angular 8 at the moment and attempting to implement a script from someone else. However, I am facing an issue due to my lack of knowledge in this area. The function in the javascript operates like this: window.X = function() { var e = argument.l ...

Troubleshooting: Why is Angular's Material Autocomplete failing to function with post requests?

I have been working on a project using Angular Material autocomplete, but I have encountered an issue where the autocomplete feature is not functioning properly. Despite my efforts to debug and identify the problem, I seem to have exhausted all possible so ...

Getting started with Angular 2 and initializing component variables

Hey there, I'm new to angular2 and currently facing a challenge. Here's the Service section: getReports() { return this.http.get(GlobalVariable.BASE_API_URL + 'report/l', {headers: this.headers}).map(res => res.json()) ...

ADAL fails to send CORS header

I've developed an Angular 5 application that utilizes the adal-angular5 package for user authentication via ADFS 2016. The Angular app interacts with an API that fetches and updates data in a connected database. The Angular app is hosted at https://lo ...

Declaring global types in a NX and NextJS monorepository for enhanced development consistency

I've been searching online to find a good solution for my issue, but so far I haven't had any luck. Currently, I have a NX monorepo with NextJS and I'm attempting to create a global types/ folder that can be accessed by all my apps and libs ...