The list filter may not work properly if the search string is left blank

I am currently working on a list filtering feature that updates based on user input. As the user types, the system compares the entered text against the items in the list and displays the matching objects in an array. However, I'm facing an issue - when the search field is empty, the original, unfiltered list should be shown instead of the last successful search result.

HTML

<input type="text" class="in-line filter" id="searchByName" placeholder="Enter a name" (keyup)="filterByName($event.target.value)" />
<study-results-table [originalArray]="originalArray"></study-results-table>

TS

ngOnInit(){
  originalArray = new Array<any>();
  unfiltered = new Array<any>()
}

filterByName(searchString){
    this.filtered = new Array<any>();           
    _.each(this.originalArray, (result) => {
        let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        if(patientName.includes(searchString.toLowerCase())){
            this.filtered.push(result);
        }
    })

    if(searchString === ""){
        this.originalArray= this.unfiltered;
    }
    this.originalArray= this.filtered;
}

Can anyone provide guidance on resolving this issue?

Answer №1

Have you thought about utilizing the array's filter function in this scenario? You could streamline your code by implementing the following:

filterByName(searchString){
    if(searchString.trim().length==0){
        this.originalArray = this.unfiltered;
        return;
    };
    this.originalArray = this.unfiltered.filter( (result)=>{
        let fullName = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        return (fullName.includes(searchString.toLowerCase()));
    });
}

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

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

AngularJS directive for automatically resizing Dygraph on page load

Could someone please assist me with resizing my graph inside tabs using Angular? When I initially load the graphs, they don't display unless I manually resize the window. How can I ensure that the graphs are loaded and fill the div on the first load? ...

Sending information from ngRoute resolve to the controller

I am currently working on an application that utilizes ngRoute to create a Single Page Application. One of the requirements is to ensure that the view is not loaded until the data has been successfully fetched from the database. While I have managed to ach ...

Create a constant object interface definition

Is there a way to create an interface for an object defined with the as const syntax? The Events type does not work as intended and causes issues with enforcement. const events = { // how can I define an interface for the events object? test: payload ...

retrieving the value of an object key based on changing information

console.log(x, obj.fares) //return undefined output adultFare Object {adultFare: "9.00", childFare: null, seniorCitizenFare: null, disabledFare: null,} How do I retrieve the adultFare value from the object? Is looping through the keys necessary? I expec ...

Leveraging angular2-material with systemjs for Angular2 development

After completing the TUTORIAL: TOUR OF HEROES on this link, I attempted to integrate angular2-material into my project. Unfortunately, I am having issues with the CSS not displaying correctly. Can anyone provide insight into what I may be missing or doing ...

String Converted to Array of Key-Value Pairs

Looking to convert a key-value pair string into a functional array? Here's what I have so far: $Array = "'Type'=>'Honda', 'Color'=>'Red'"; $MyArray = array($Array); However, this code is not returning a ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

Is there a way to verify the visibility of an element in Protractor?

Currently, I am utilizing Protractor for conducting my comprehensive end-to-end tests. A few elements have been configured with ng-show attributes. Would someone kindly advise me on how to validate whether these elements are visible or not using Protracto ...

Causes of encountering unexpected data in output while printing a 2-D array using pointers

I need assistance with a situation involving a pointer to a dynamically allocated 2-D array. When I try to print the values of the array by dereferencing the pointer, some of the indices display garbage values even though they were initialized to 1. Any ad ...

What is the best way for a parent process to interrupt a child_process using a command?

I'm currently in the process of working on a project that involves having the user click on an 'execute' button to trigger a child_process running in the backend to handle a time-consuming task. The code snippet for this operation is shown b ...

The parameter in Angular cannot be assigned a type of 'null'

@Injectable({ providedIn: 'root' }) export class AuthenticationService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.curren ...

How can I shrink a PHP array into a significantly smaller JSON file?

I have a PHP array coming from a webservice (soap xml) that I want to filter and convert to JSON (refer to the example below). Check out the sample of the array received from the webservice: (*** indicates the data needed in the final JSON) {"Id":445946 ...

Unraveling the Mystery of the JavaScript forEach() Function

Exploring the use of nodejs in Ubuntu and delving into the MDN documentation for the JavaScript forEach() method. While aware of alternative methods, I find that hands-on learning suits me best; my current goal is to create a unique array named copy, conta ...

Is it better to utilize angular's $interval or a promise to execute code upon completion of an api call?

I am facing an issue with a slow api call in my code. $http.jsonp(url, { params: { 'client': 'translate_about', 'alpha': 1, 'hl': 'en' } }) .success(function (data) { ...

Issue with displaying value from page in AngularJS modal when clicked

How can I get the data copied from my page's $scope element (thisRequest) into my modal's $scope element (nTask) to display correctly in the modal after clicking a button in AngularJS? You can view the code on this Plunker. Here is an example o ...

optimize the highest value in the stack through precisely K operations

There is a stack of N integers, and the goal is to maximize the top element after exactly K operations. Each operation involves either popping an element from the stack or pushing any popped element back into the stack. If the stack becomes empty after K o ...

Ways to recover information that is not typically found

My firebase database has two main trees: "tag" and "user". Each user is associated with a set of tags, referred to as preferences. Here is the structure of my database: I am trying to display a list of preferences that a specific user does not have. Exam ...

TSLint now requires promises to be handled correctly using the `finally` clause

Encountering an error from TSLint, I am working to comprehend why it is raising concerns. In my code, there is a function that calls another method which returns a promise. However, the initial function does not return the promise; instead, it waits for c ...

Issue with rest operator behavior in TypeScript when targeting es2018

This specific code snippet functions properly in the TypeScript Playground... class Foo { constructor(...args: any[]) { } static make(...args: any[]): Foo { return new Foo(...args); } } Example However, when trying to incorpora ...