Is there a way I can replace this for loop with the array.some function?

I am looking to update the filterOutEmails function in the following class to use array.some instead of the current code.

export class UsertableComponent {
  dataSource: MatTableDataSource<TrialUser>


  createTableFromServer = (data: TrialUsers[], emailDomains:string) => {
    this.dataSource = new MatTableDataSource(data);
    this.dataSource.filterPredicate = this.filterOutEmails;
  } 

  filterOutEmails = (row: TrialUser, emailDomains: string): boolean => {
    const listofFilters = emailDomains.split(',');
    for (let i = 0; i < listofFilters.length; i++){
      if (row.email.toLowerCase().includes(listofFilters[i].trim())){
        return true;
      }
    }
    return false;
  }
}

I attempted to make the change using a separate determineIfRowShouldBeShown method but ran into issues with "this". I also tried using an arrow function inline, which worked. However, I prefer to keep the function definition separate.

private determineIfRowShouldBeShown(this: TrialUser, domain: string): boolean {
  const row: TrialUser = this;
  return !row.email.toLowerCase().includes(domain.trim());
}

private filterOutEmails= (row: TrialUser, emailDomains: string): boolean {
  const listofFilters = emailDomains.split(',');
    return listofFilters.some(this.determineIfRowShouldBeShown, row) ;
  }
}

Answer №1

When utilizing an arrow function, the binding of this remains lexical even when passed as an argument:

// If you're going to manipulate `this`, it's not recommended to place the function within a class where `this` can be confusing if it doesn't refer to the instance. Arrow functions also prevent context rebinding in this scenario.
function determineIfRowShouldBeShown(domain: string): boolean {
    return !this.email.toLowerCase().includes(domain.trim());
}

export class UsertableComponent {
  dataSource: MatTableDataSource<TrialUser>;

  createTableFromServer = (data: TrialUsers[], emailDomains:string) => {
      this.dataSource =  new MatTableDataSource(data);
      this.dataSource.filterPredicate = this.filterOutEmails
  }
  // The method name 'filterOutEmails' may be misleading as it does not actually perform filtering.
  filterOutEmails(row: TrialUser, emailDomains: string): boolean{
    return emailDomains.split(',').some(determineIfRowShouldBeShown, row);
  }
}

Other approaches to achieving the same functionality include:

Manual binding of the function:

...
filterOutEmails(row: TrialUser, emailDomains: string){
  emailDomains.split(',').some(determineIfRowShouldBeShown.bind(row));
}

Utilizing currying or partial-application (personal preference)

const determineIfRowShouldBeShown = (row: TrialUser) => (domain: string): boolean => !row.email.toLowerCase().includes(domain.trim());
...
filterOutEmails(row: TrialUser, emailDomains: string){
  emailDomains.split(',').some(determineIfRowShouldBeShown(row));
}

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

Turning a string array into a basic array can be achieved through a few simple steps

While I am aware that this question has been posed multiple times, my scenario is slightly unique. Despite exhausting numerous methods, I have yet to discover a suitable workaround. $array = ["9","8","7","6","5"]; //result of javascript JSON.stringify() ...

"PHP, AJAX, and JavaScript work together to run a loop that processes only the final element

Hello everyone, I need assistance in saving data from a loop. Here is the code snippet that I am working with: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> ...

Transforming Angular 4's folder structure for improved architecture simplicity

I am faced with the challenge of organizing files and folders within an Angular 4 project in a way that allows for easy reorganization. Currently, my approach looks like this: ├───core │ │ core.module.ts │ │ index.ts │ │ │ ...

Why doesn't TypeScript automatically determine the prop type when Generics are used?

Below is the code snippet: interface MyInterface { a: { b: { c: "c"; }; }; } type ParentProps = keyof MyInterface type ChildProps<ParentProp extends ParentProps> = keyof MyInterface[ParentProp] type GrandChildType< ...

Trouble encountered with the implementation of setValue on placeholder

When I send the value for age, it is being treated as a date in the API that was built that way. However, when I use setValue to set the form value and submit the form, it also changes the placeholder text, which is not what I want. I would like the placeh ...

The array's value fluctuates into a negative without any direct manipulation from my end

In order to work with the $scope.option value, I stored it in a temporary variable and then applied operations on the temporary variable after changing all the values of $scope.option to negative numbers. var app = angular.module('myApp', []); ...

Java: troubleshooting search function crashes in 2D arrays

For my introduction to CS class, I am working on developing a reversi game. In the process, I noticed an issue in the SearchN() function that could result in incorrect playable flag values. To address this problem, I introduced the isSame() function as a ...

Utilizing C programming to handle an array of character pointers

In the process of designing a program, I am working on extracting strings from a text file and storing them in an array. For instance, if the delimiters extracted from the text file are: "one", "dfs", "w342" Once these delimiters are obtained, the object ...

Including a Javascript library (jsencrypt) in an Angular 2 application

I have gone through countless tutorials on this particular issue, but unfortunately, I have not yet found a solution. Let me provide some context first. I am working on an Angular 2 application and I need to incorporate this JS library for encryption: http ...

In Angular 5, what is the best way to transform an array into an object and cycle through a list of

JSON: The JSON I have contains a list of userids that I want to iterate through, but I'm having trouble fetching the content in a list format. { "data": { "items": [ { "regions": "India", "owner ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

What's causing the repeated occurrence of ".class expected here"? None of the typical issues seem to be to blame

After reviewing multiple instances, I found that the typical issues stem from code not being within a method or incorrect bracketing. However, I have thoroughly checked for these errors in my code. Here is what I have written: import java.util.*; public ...

Eliminate items from a list that have duplicate properties

I have a collection of objects, each with a unique NAME property. However, there are duplicates in the collection where some objects share the same NAME. const arr = [ {name: "x", place: "a", age: "13" }, {name: "x", place: "b", age: "14" }, { ...

Sending a POST request in Angular5 using the HTTP module

Angular 5 Attempting to create a function that will generate a resource on my API using Angular has proven to be a challenge. The "employee.service.ts" file contains a method named "saveEmployee" which is triggered by a function called "addEmployee" locate ...

The issue with Rxjs forkJoin not being triggered within an Angular Route Guard

I developed a user permission service that retrieves permissions from the server for a specific user. Additionally, I constructed a route guard that utilizes this service to validate whether the user possesses all the permissions specified in the route. To ...

Converting an array of objects to an array of JSON objects in TypeScript

My dilemma lies in the data I have uploaded under the _attachments variable: https://i.sstatic.net/jnFNH.png My aim is to format this data for insertion in the following structure: "_attachments": [ { "container": "string", "fileName": "string" ...

Using PHP to generate JSON arrays from MySQL data for displaying in Highcharts

Need help with configuring Json output for my highchart scatter plot? Check out this example. Here is the desired Json output: [{ "name": "Female", "color": "red", "data": [{ "name": "Anna", "x": 161.2, ...

UPDATE: Choosing several classes and then toggling the classes independently for each one

I have managed to make this work, but I am considering if there is a more efficient solution. My objective is to modify the divs using classes exclusively. I aim to toggle 4 classes with just one click. First, I obtain the class for the button and then a ...

Beautiful parentheses for Typescript constructors

I'm working on a project where I've installed prettier. However, I've noticed that it always reformats the code snippet below: constructor(public url: string) { } It changes it to: constructor(public url: string) {} Is there any way to sto ...

Using TypeScript to automatically deduce the output type of a function by analyzing the recursive input type

I am currently working on developing an ORM for a graph database using TypeScript. Specifically, I am focusing on enhancing the "find" method to retrieve a list of a specific entity. The goal is to allow the function to accept a structure detailing the joi ...