What is the best method for quickly filtering an array of objects according to the user's input?

What seemed like a simple task has me puzzled. I'm trying to sort through an array of objects based on user input.

[{ name: Stan, age: 20, height: 190 },
{ name: Pan, age: 30, height: 180 },
{ name: Dan, age: 28, height: 185 },
{ name: San, age: 20, height: 170 }]

For example, if a user types 'S', they should get 'Stan' and 'San'. If they type 'St', it should narrow down to just 'Stan', and so on with real-time results displayed.

I've attempted to filter the array by first letter and then try to refine it further based on subsequent inputs by pushing results into another array, but it's not working as expected. So now, I find myself at a standstill.

filterCat() {
    this.cate.filter(cat => {
        if (cat.name.startsWith(this.searchTerm.toUpperCase())) {
            this.tempSearchStore.push(cat);
            console.log('cats', cat);
        }
        // This displays all cats based on the first letter entered.
    });
}

This is my HTML:

<ion-searchbar animated [(ngModel)]="searchTerm" debounce="1000" 
  (ionChange)="filterCat()" mode="ios">
</ion-searchbar>

Answer №1

How about trying this code snippet:

this.pets = [{name:'Max', age:5, weight:20},
{name:'Charlie', age:3, weight:15},
{name:'Buddy', age:7, weight:25},
{name:'Lucy', age:4, weight:18}]


function filterPet(searchTerm: string) {
 return this.pets.filter(pet => pet.name.toUpperCase().startsWith(searchTerm.toUpperCase()));
}

console.log('Filter L');
console.log(filterPet('L'));

console.log('Filter Lu');
console.log(filterPet('Lu'));

this.filteredPetsList = filterPet('Lu')

and try using:

<div *ngFor="let pet in filteredPetsList ">{{pet.name}}</div>

You just need to provide the search term to the function

Answer №2

The startsWith() method is sensitive to case, meaning that if you are converting each letter of the searchTerm to uppercase, your condition will fail. To fix this issue, consider implementing the following:

if (cat.name.startsWith(this.searchTerm.charAt(0).toUpperCase() + 
    this.searchTerm.slice(1))) {

    this.tempSearchStore.push(cat);
    console.log('cats', cat);
}

Check out this

Stackblitz

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

Do not send the Angular 2 HTTP request with headers

As someone new to Angular2, I am working on building a data service and trying to include headers in each request. Here is my attempt at adding headers, but for some reason they are not being sent: import { Injectable } from '@angular/core'; im ...

What could be causing the failure to typecheck the sx prop?

Trying to implement sx prop-based styling in a React project. Looking to utilize the theme using a theme getter. While styles render correctly in the browser, TypeScript raises errors and understanding the type ancestry is proving challenging. Working e ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

Exploring Data in Angular 2: Examining Individual Records

I am currently learning Angular and facing some challenges in structuring my questions regarding what I want to achieve, but here is my query. Within a component, I am retrieving a single user record from a service. My goal is to display this user's ...

How can you export the type of a private class in TypeScript without exporting the class itself?

I am facing a dilemma in my module where the public method of a public class is responsible for creating and returning a new instance of a private class. The stipulation is that only MyClass should have the capability to instantiate MyClassPrivateHelper. ...

Can you provide any instances of Angular2 projects with intricate routing, specifically with version 2.0.0-rc.1?

Currently, I am in the process of building a web application with angular2 (2.0.0 rc 1) and encountering obstacles due to the insufficient documentation, especially when it comes to establishing intricate routing. Since version 2.0.0 was just released app ...

What is the reason behind TypeScript choosing to define properties on the prototype rather than the object itself?

In TypeScript, I have a data object with a property defined like this: get name() { return this._hiddenName; } set name(value) { ...stuff... this._hiddenName = value; } However, when I look at the output code, I notice that the property is on ...

Is there a circular dependency issue with ManyToMany relationships in Typescript TypeORM?

Below are the entities I have defined. The Student entity can subscribe to multiple Teachers, and vice versa - a Teacher can have many Students. import { PrimaryGeneratedColumn, Column, BeforeInsert, BeforeUpdate } from "typeorm" /* * Adhering to ...

Pass the previousItem to the click event handler within the *ngFor loop

Could I possibly retrieve the previous value of an item in an *ngFor loop when a specific event like click() is triggered? For instance: <myItem *ngFor="let data of dataList"> <div (click)="onClick(data, prevData)"> </myItem ...

Steps for sending data from Angular2 or Angular4 to a Node.js server and saving it in a MySQL database:1. In your

I've scoured the depths of the internet on Google but have come up empty-handed in finding a reliable working example. Any assistance would be greatly appreciated as I am relatively new to Angular2 (angular4). My goal is to have my angular2 applicati ...

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

How can I ensure thorough test coverage without relying on Testbed?

We have implemented some custom form control components with decorators as follows: @Component({ selector: 'value-selector', templateUrl: './selector.component.html', styleUrls: ['./selector.component.scss'], provid ...

When implementing useReducer with TypeScript, the error "Argument of type '(type, action) => { state: (...}' is not assignable to parameter of type 'ReducerWithoutAction<any>'" may occur

Recently, I decided to delve into learning TypeScript by building a simple shopping cart application. If you want to check out the code, feel free to visit my GitHub repository: https://github.com/CsarGomez/shopping-cart-reducers-tx I've encountered ...

Different methods to initiate multiple calls using the dispatch function within ngrx

Utilizing NGRX to dispatch the IDs from an array, I am facing the challenge of needing to make multiple simultaneous calls instead of looping through them in ngOninit. Here is the code snippet for dispatch: loadEmloyeePricing(): void { let id = []; ...

How to ensure Service is loaded before App Component in Angular 6?

My Data service is responsible for fetching the JSON Object value, however all components load before the data service finishes loading. This results in undefined values when I call the service method from components. ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

Encountering an emscripten error when using MediaInfo.js with Angular 16

Trying to integrate mediainfo.js with Angular 16 based on the documentation found at https://github.com/buzz/mediainfo.js. Following the documentation, we have installed the necessary dependencies : Installation : "@types/emscripten": "^1. ...

Utilizing TypeScript Class Inheritance: The Reference to 'super' is Only Allowed in Members of Derived Classes or Object Literal Expressions

We have encountered a scoping issue while using TypeScript classes with inheritance. It seems that TypeScript/JavaScript does not allow us to use 'super' within a promise structure or an enclosed function. The error message we are getting is: Ty ...

A step-by-step guide to enabling editing for a specific row in a Primeng DataTable in Angular 2 with just the click of

I'm currently working on implementing DataTable from Primeng in Angular 2. The datatable displays a set of rows with an Edit button for each row. When the Edit button of any row is clicked, all fields of that particular row should become editable. ...

The parameter type '{ email: string; }' in NGXS does not accept arguments of type 'string'

Struggling to retrieve data from an API using ngxs with this.store.dispatch(new GetUser(userEmail)) Attempted to use the user id stored in local storage as a string and convert it to a number but encountered a similar error (Argument of type 'string&a ...