Using Typescript to pass arrays as parameters

I'm refactoring my code to consolidate multiple functions into one, but I'm having trouble updating an array passed as a parameter. The function itself is functioning correctly, but the array doesn't update within the class.

In this TypeScript class, the commented-out code in the `onCompanyRenterNameChanged` function works fine. However, the new code below the comment isn't updating the `filteredListOfRenters` array that's being passed as a parameter. Even after running it, the function returns the full list instead of the filtered list, and I can't figure out why.

export class FilterDialogComponent implements OnInit {
  filteredListOfRenters: Company[];
  filteredListOfStatuses: Status[];
  filteredListOfCars: Car[];

  constructor(...) {
  }

  ngOnInit() {
    this.fillFilteredListsOnInit();
    this.selectValueInControl();
  }

  confirmFilter(data): void {
    data.renterId = this.filterFormGroup.get('renterControl').value;
    data.statusId = this.filterFormGroup.get('statusControl').value;
    data.carId = this.filterFormGroup.get('carControl').value;
    this.dialogRef.close({
      data
    });
  }

  onCompanyRenterNameChanged(value: string) {

    //this.fillFilteredListOfRenterCompanies(value.toLowerCase());
    this.fillFilteredList(this.codeListService.listOfRenters, this.filteredListOfRenters, value.toLowerCase());
  }

  onStatusChanged(value: string) {
    this.fillFilteredListOfStatuses(value.toLowerCase());
  }

  onCarChanged(value: string) {
    this.fillFilteredListOfCars(value.toLowerCase());
  }

  fillFilteredList(codeList: any[], filteredList: any[], filter: string){
    if(codeList.length !== 0){
      filteredList = codeList.filter((item) => {
        if(item.name !== null){
          return item.name.toLowerCase().startsWith(filter);
        }
      })
    }
  }

  fillFilteredListOfRenterCompanies(filter: string) {
    if (this.codeListService.listOfRenters.length !== 0) {
      this.filteredListOfRenters = this.codeListService.listOfRenters.filter((item) => {
        if (item.name !== null)
          return item.name.toLowerCase().startsWith(filter);
      });
    }
  }

  fillFilteredListOfStatuses(filter: string) {
    if (this.codeListService.statuses.length !== 0) {
      this.filteredListOfStatuses = this.codeListService.statuses.filter((item) => {
        if (item.name !== null)
          return item.name.toLowerCase().startsWith(filter);
      });
    }
  }

  fillFilteredListOfCars(filter: string) {
    if (this.codeListService.cars.length !== 0) {
      this.filteredListOfCars = this.codeListService.cars.filter((item) => {
        let carName = this.codeListService.getNameOfManufacturerById(item.manufacturerId) + " " + item.model + " " + item.ecv;
        if (carName !== null)
          return carName.toLowerCase().startsWith(filter);
      });
    }
  }

  fillFilteredListsOnInit(){
    this.filteredListOfRenters = this.codeListService.listOfRenters;
    this.filteredListOfStatuses = this.codeListService.statuses;
    this.filteredListOfCars = this.codeListService.cars;
  }
}

Answer №1

By using Array.filter, you are setting filteredList to a new array. For more information, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter.

To achieve what you intend, make sure to return the new results from the function and then assign them back to the array variable.

onCompanyRenterNameChanged(value: string) {
    filteredArray = this.fillFilteredList(this.codeListService.listOfRenters, 
    this.filteredListOfRenters, value.toLowerCase());
}

fillFilteredList(codeList: any[], filteredList: any[], filter: string){
    if(codeList.length !== 0){
      return codeList.filter((item) => {
        if(item.name !== null){
          return item.name.toLowerCase().startsWith(filter);
        }
      })
    }
    else {
        return [];
    }
 }

Answer №2

Make sure to retrieve the final outcome.

Execute the following code update:

  getFilteredItems(itemsList: any[], filteredList: any[], keyword: string){
    if(itemsList.length !== 0){
      filteredList = itemsList.filter((item) => {
        if(item.name !== null){
          return item.name.toLowerCase().startsWith(keyword);
        }
      });
      return filteredList 
    }
    return []
  }

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

There seems to be an issue with the compilation of TypeScript

I got my hands on the Typescript + AngularJS example downloaded from this source: The issue I'm facing is that whenever I compile it using Visual Studio, the references don't seem to be compiled properly. However, if I utilize the command prompt ...

Authentication dependencies in Angular Services (Version 17)

Within my angular application, I have successfully integrated user authentication alongside a recipe library that is specific to each individual user's account. To achieve this functionality, I've employed an AuthService and a RecipeService. Howe ...

A dynamic d3 line chart showcasing various line colors during transitions

I have implemented a d3 line chart using this example as a reference: https://codepen.io/louisemoxy/pen/qMvmBM My question is, is it possible to dynamically color the line in the chart differently based on the condition y > 0, even during the transitio ...

The concept of ExpectedConditions appears to be non-existent within the context of

Just starting out with protractor and currently using version 4.0.2 However, I encountered an error with the protractor keyword when implementing the following code: import { browser } from 'protractor/globals'; let EC = protractor.Expe ...

Troubleshooting: Why is .detectChanges() not functioning as expected

My current task involves writing tests for a chat application built with Angular. I am focusing on testing the following Angular template code snippet: <div class="title-menu-container" fxLayoutAlign="center center"> <button id="save-title-butt ...

The user callback for @firebase/database encountered an exception. TypeError: Unable to access property 'myID' as it is undefined

After deploying my app to Firebase hosting, some users are encountering this error: @firebase/database: FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot read property 'myID' of undefined screenshot https://i.sstatic ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

The Ionic 2 MEAN App fails to provide the latest data upon sending a GET request

Something strange is happening with the application that I'm developing. I have a function that reads a user's game statistics - Wins, losses, draws etc. This function uses a service to create an observable and retrieve data from my rest API. The ...

Sending properties via react router link in TypeScript

I have successfully defined my routes and made my links functional. I am now trying to figure out how to pass a prop through the link when the component is called by the router. It seems like a challenging task. To understand better, take a look at this c ...

Set the default page for the p-table

My English proficiency is lacking. I am currently using a p-table with pagination, but I need to modify the pagination in the HTML code. <p-table #dt [columns]="cols" [value]="values" [paginator]="true" [rows]="10" (onFilter)="filtra ...

Achieving seamless integration among react-templates, TypeScript, and webpack

I am attempting to integrate TypeScript, react-templates, and webpack for a seamless workflow. My starting point was the sample code provided at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html. The configuration in the webpack.config ...

It can be time-consuming to render a large quantity of dynamic markers on Leaflet after receiving a response

Incorporating leaflet.js into my web project, I am faced with the challenge of creating a map view with dynamic markers. Upon receiving a response, I attempt to generate dynamic components based on the data and utilize change detection to monitor updates. ...

Obtaining file image input in TypeScript

I am struggling to integrate a file uploaded via the input type "file" into my Fabric JS canvas. The steps of the process are as follows: User initiates action by pressing a button (calls onAddImage) User selects an image to upload Selected image is adde ...

What causes the arrays to be empty when sending form data with .NET API in conjunction with React?

The structure of the DTO is as follows: public List<IFormFile> Images { get; set; } public int[] Numbers { get; set; } The method signature is: public async Task<IActionResult> AddSection([FromForm]TheDto theDto) To add the form data in React ...

obtaining the status of a checkbox in ionic2

Here is the scenario: I am managing a list of users. Additionally, I have a collection of items where each item contains an array of associated users. The display of the items list is as follows: <ion-list> <ion-item *ngFor="let item of it ...

Having trouble with implementing Spotify OAuth in NextJS?

I am in the process of creating a music website portfolio using Spotify and NextJS. I want to incorporate music playback on the website, but I am encountering issues with Spotify authentication. When I click the login button, I receive a 405 HTTP status er ...

The Angular Compiler was found to be the incorrect class instance, causing issues with the project's build process

error snapshot It appears that an incorrect instance of the Angular Compiler was detected, indicating the presence of multiple @ngtools/webpack packages. To verify this, you can use the command npm ls @ngtools/webpack and proceed to remove any duplicate c ...

Experiencing difficulty with nested navigators in react navigation, struggling with

I am currently working on a tab navigator with Home and Profile screens. Within the Home screen, there is a stack navigator containing the RestaurantDetails and RestaurantList screens. My issue lies with a Button located in the RestaurantList screen. I am ...

Analyzing the value of a tab with Protractor测试

Below is my HTML code showcasing a list of tabs: <mat-tab-group> <mat-tab label="A"> <app-A></app-A> </mat-tab> <mat-tab label="B"> <app-B></app-B> </mat ...

Setting Up Absolute Imports in Node.js using TypeScript

I recently completed a project in Node using TypeScript, and I am currently experimenting with implementing absolute paths for imports. However, upon running the project, it starts to fail with the following error message: [1] Error: Cannot find module &a ...