Grid filtering challenges

I have implemented a filtering pipe logic for grid search.

results.filter(item => Object.keys(item)
          .some(key => searchTerm.split(',').some(arg =>item[key]? item[key].toString().toLowerCase().includes(arg.toString().toLowerCase()):""))
         ); 

The code above searches for a keyword in all columns in the array list, which is bound to the grid. However, I only want to search through the columns that are displayed in the grid.

So, the revised logic will be as follows:

results
          .filter(item => (item.ProxyName.toLowerCase().includes(searchTerm.toLowerCase()) || 
                            item.ProxyType.toLowerCase().includes(searchTerm.toLowerCase())||
                            item.SA_SPOC_DL.toLowerCase().includes(searchTerm.toLowerCase())||
                            item.AssignmentGroup.toLowerCase().includes(searchTerm.toLowerCase()))
                  );
         .filter(item => Object.keys(item)
          .some(key => searchTerm.split(',').some(arg =>item[key]? item[key].toString().toLowerCase().includes(arg.toString().toLowerCase()):""))
         );  

To enable this, I decided to pass a comma-separated array of columns to filter like so:

string searchcolumns = ["ProxyName,ProxyType,SA_SPOC_DL"]

If I pass a comma-separated array of columns, how should I rewrite the logic?

Answer №1

I made some improvements to the code by focusing on optimizing the column usage. Instead of altering other parts of your logic, I simply refactored the section that handles column iteration:

const itemList: any[] = [
  { ProxyName: 'AG', AssignmentGroup: 'AG', ProxyType: 'PT', SA_SPOC_DL: 'SA2' },
  { ProxyName: 'B1', AssignmentGroup: 'AG123', ProxyType: 'AG', SA_SPOC_DL: 'SB2' },
  { ProxyName: 'C1', AssignmentGroup: 'AG', ProxyType: 'PT', SA_SPOC_DL: 'SC2' },
  { ProxyName: 'D1', AssignmentGroup: 'A', ProxyType: 'PT', SA_SPOC_DL: 'AG' },
  { ProxyName: 'E1', AssignmentGroup: 'AG', ProxyType: 'PT', SA_SPOC_DL: '' },
  { ProxyName: 'F1', AssignmentGroup: 'A', ProxyType: 'PT', SA_SPOC_DL: '' }
];

const searchColumns = ['ProxyName', 'ProxyType', 'SA_SPOC_DL', 'AssignmentGroup'];

const result = filterResult('AG', searchColumns, itemList);

function filterResult(searchTerm: String, searchcolumns: string[], results: any[]) {
  const resultSet: any[] = [];
  searchcolumns.forEach(column => {
    results.filter(item =>
      item[column].toLowerCase().includes(searchTerm.toLowerCase())
      && !resultSet.includes(column)
    ).filter(item => Object.keys(item)
      .some(key => searchTerm.split(',')
        .some(arg => item[key] ? item[key].toString().toLowerCase().includes(arg.toString().toLowerCase()) : '')))
      .forEach(element => { if (!resultSet.includes(element)) { resultSet.push(element); } });
  });

  return resultSet;
}

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 the NavBar be refreshed once a user logs in?

I recently followed a helpful guide on implementing a login system in my React TS application. However, I encountered an issue with the NavBar component within my app compared to how it was coded in the App.tsx file of the guide. Specifically, I found it c ...

Connecting Angular forms to retrieve form data using email

Hello, I am new to Angular and haven't had experience hosting a website before. I have created a contact form on my website and would like the form inputs to be sent to my email address whenever someone submits the form. Can anyone guide me on how to ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

What is the best method for inserting multiple values into an array key and retrieving data from a different table?

My current task involves retrieving data from a database based on the condition that the id matches the tenant_id of the currently logged-in user, $this->data['props'] = $this->property_m->get_by( array ('id' => $this->s ...

Ways to add animation to my header while it transitions

My app has a simple layout with a header at the top and a content container below it: <div class="main" [@applicationTransition]="applicationState" fxLayout="column" fxFlexFill> <nav class="header"> <!-- insert header content & ...

Using Typescript file for importing configurations instead of relying on json files dynamically

Let me give you some context: Our team is working on creating AWS CDK modules using Typescript (just so you know, I'm not very experienced in TS). One of the modules we're developing is for managing container-based applications that developers c ...

Is the lazy loading feature for nested modules in an Angular Ionic4 application experiencing functionality issues?

My application includes both public routes like login and register, as well as protected routes for members. The member routes contain child routes within tabs, with additional child routes for categories, items, and more. However, when running 'ionic ...

retrieving the final element from a multidimensional array

I have an array that holds values for enquiries, quotes, and orders for each month over a period of time. I want to organize this data by creating sub-arrays for each month to store the corresponding values. However, when I try to access these values using ...

Is it possible to remove the selected item from the list within the array

I have a program that reads a text file during startup to populate an array, which is then used to fill a listBox. Now I want the user to be able to select an item in the listBox and delete it. When an item is deleted, I need the array to update accordingl ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Navigating concurrency problems in NodeJS when using Redis

My requirement Retrieve a token from Redis that is not already reserved for an application (its application value is not set). Assign the retrieved non-reserved token to a specific application, ensuring other threads do not get the same token for reservat ...

Multiple consecutive requests within another (Angular)

Currently, I am deepening my understanding of rxjs and struggling to find an efficient way to manage a sequence of requests. For instance, let's consider the UserService where one of its functions retrieves a user object based on the user id. After ob ...

How can I replace document.getElementById in Angular4 using Typescript?

Angular4 is a new concept for me as I work on my practice projects. To access HTML elements and retrieve their values, I have been using <HTMLInputElement> document.getElementById or <HTMLSelectElement> document.getElementById. I'm curio ...

Include files from an array without the need for specifying individual file paths

I need to consolidate attachments from draft emails (created automatically by another program) into one email with potentially multiple attachments. There are three arrays involved: attachments arrAtt() (from the original draft emails) original draft&apo ...

Typescript throwing an exception for a properly defined parameter

Using a combination of NextJs and typescript, I am encountering an issue when passing a correctly typed prop. The error that is displayed is as follows: ./pages/jobs.tsx:100:15 Type error: Type '{ job: jobType; key: number; handleTagClick: (tag: strin ...

Combine values from multidimensional array into a single array

I have an array in the following format. Array ( [0] => Array ( [keyword] => thumbnail_follow [content] => width ) [1] => Array ( [keyword] => thum ...

Save the chosen column value from an Excel spreadsheet into an Array by utilizing column letters in C# Excel Interop

As I work with Excel to import records into the program I am developing, my usual method involves retrieving data from Excel and storing it in an array using column indexes. Here's how I usually do it: Excel.Range xlRange = xlWorksheet.UsedRange; str ...

Pass the parameter name to the controller using the Change function in Angular 2

When creating a string from multiple inputs, I have a requirement to include the name of the input element as the second parameter in a function. <input [(ngModel)]="programSearched" name="programSearched"(ngModelChange)="stringBuilderOnChangeMaker(pro ...

Tips for configuring TypeScript in a monorepo to successfully compile private packages

I have configured a monorepo using turborepo that includes Nestjs for the backend and Nextjs for the frontend. To reuse prisma definitions, I separated them into their own package with its own tsconfig. In the index file of my database package where prism ...

Designing a schema using mongoose and typescript

I have been attempting to create a new mongoose schema, but I keep encountering an issue where the new collection only contains two columns: _id and __v. None of the columns from my schema are included. Here is the code for the schema: import DataAccess f ...