Looking for elements that match in an array

Currently working on a basic program that requires checking if the input string exists in the array.

To simplify it, for example, if someone types 'Ai', I want the program to display all elements in the array containing the letters 'Ai'. The result should include words like 'Airplane', 'Air', 'Airport', and 'Airfield'.

If anyone has a quick and simple solution for achieving this, your help would be greatly appreciated!

Answer №1

If you have an array consisting of only strings, the following functions can be used to perform the required actions:

// Function to find if any string in the array contains a specific substring.
function checkStringInArray(array: string[], str: string)
{
    let filteredArray = array.filter(x => x.includes(str));
    return filteredArray.length > 0;
}

// Function to find if any string in the array starts with a particular string.
function checkStringStartsWith(array: string[], str: string)
{
    let filteredArray = array.filter(x => x.startsWith(str));
    return filteredArray.length > 0;
}

Example program for testing:

let testStr: string = "air";
let exampleArr1 = ["corsair","stenographer"];
let exampleArr2 = ["hey","no"];

function checkStringInArray(array: string[], str: string)
{
    let filteredArray = array.filter(x => x.includes(str));
    return filteredArray.length > 0;
}
function checkStringStartsWith(array: string[], str: string)
{
    let filteredArray = array.filter(x => x.startsWith(str));
    return filteredArray.length > 0;
}
console.log(checkStringInArray(exampleArr1, testStr));
console.log(checkStringInArray(exampleArr2, testStr));
console.log(checkStringStartsWith(exampleArr1, testStr));
console.log(checkStringStartsWith(exampleArr2, testStr));

Output:

true false false false

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

Resolving the Issue: How to Solve the "Missing Required Request Body" Error in Angular and Spring MVC

I'm encountering an issue with removing a product from the database using Angular on the frontend. The error message I am receiving is: Required request body is missing: public boolean prodcust.controller.DeleteController.deleteProduct(java.lang.Stri ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

Troubleshooting issue: Angular dropdowns not functioning properly with Bootstrap framework

Despite importing Bootstrap 4 and other necessary libraries like jquery and popper into my Angular app using npm, I am facing an issue where the dropdown in the top navigation bar does not work. I am hesitant to bring in additional Angular Bootstrap librar ...

Nexus and GraphQL: The root typing path for the "context" type is not found

I’m currently working on integrating GraphQL into Next.js API routes. For writing the GraphQL schema, I’m utilizing Nexus. Here are the two essential files: context.ts and schema.ts, that help in setting up Nexus development mode. // context.ts import ...

Unable to pass response from httpclient post method to another custom function in Angular 4

I've implemented the addUser(newUser) function in my sign-in.service.ts file like this: addUser(newUser) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JS ...

Bring in a class with an identical name to a namespace

Currently, I am utilizing a third-party library that comes with a separate @types definition structured as follows: declare namespace Bar { /* ... */ } declare class Bar { /* ... */ } export = Bar; How should I go about importing the Bar class into my ...

Updating a query parameter with jQuery

Looking for a way to modify the value of a query parameter in a URL using jQuery. There are two example URLs: www.domain.com/?id=10&name=xxx and www.domain.com/?name=xxx&id=10 I want to update the id parameter to something like www.domain.com/ ...

Various array outcomes are produced by identical JavaScript (SAP UI5) code

Utilizing cachebuster to identify the modified file in the application structure. Javascript code snippet: https://i.sstatic.net/CZGfW.png Ineffective Array result: https://i.sstatic.net/D6MdS.png Effective Array result: https://i.sstatic.net/pQCIh.p ...

What is the approach taken by Angular when it comes to managing dependency injection for a variety

In my project, I've designed an abstract class that serves as a foundation service for my other two services. Below is the snippet of code for this abstract class: import { Injectable } from '@angular/core'; export interface Book { title ...

Searching Text Boxes with Javascript: A Better Way to Handle Arrays

I'm struggling to implement a feature where users can search for authors in a database and be redirected to the corresponding HTML if found. Otherwise, it should display a message saying "No Author Found"... I need some assistance in getting this fun ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

Using Inheritance to Create Custom Event/Callback Handlers in TypeScript

Currently facing an issue with Typescript that I'm stuck on. I have created a named callback Handler class that receives the allowed list of "events"/"handlernames" as a generic: class NamedHandler<H extends { [key: string]: HandlerFunction }> ...

Using ngIf with Promises causes a malfunction

I have extensively tested this issue and I am unable to understand why the code below is not functioning as expected. The problem arises when the @Input variable is received and the user object is fetched from the service, the ngIf directive in the templat ...

What methods can be used to protect an application with spring boot and angular 8 without requiring users to log in?

I am looking to enhance security for an application that leverages angular 8 and spring boot 5. Currently, the application is free form and does not require login to access the UI. Although I have implemented CSRF protection, it is still possible for som ...

The table component in Primeng is encountering issues when being used with ngFor

I'm attempting to iterate through an array where each object represents a table in HTML, and it should be displayed like this: <p-table [value]="section" *ngFor="let section of sections"> <ng-template pTemplate="header"> <t ...

Encountered an error while attempting to run the org.apache.maven.plugins:maven-jar-plugin:2.6:jar goal

Currently, I'm engaged in a comprehensive project that involves both backend and frontend development. The frontend aspect (built on the angular2 framework) is functioning smoothly with commands like 'npm start' and 'ng build'. How ...

Transform Firestore JSON data into a TypeScript array

Extracting and formatting data from Firebase for visualization purposes can be challenging after successfully working with it in HTML. I am currently dealing with a FirebaseListObservable that contains three value-types, but only one of them needs to be in ...

Unable to display custom component on app.component.html

After creating a unique custom component named core.component, I proceeded to import it into a module with the same name. core.component.html <div class="container-fluid text-left"> <div class="row rows-cols-2 top-bar"> ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Attempting to connect information to state using an input field that is being iterated over in React

Struggling with binding state values to input values using an onChange function handleChange = event => { this.setState({ [event.target.name]: event.target.value }); }; The issue arises when the Input fields are within a map and assi ...