Instructions on incorporating a regular expression test within an array find operation

My array looks like this:

const arr = [{id: "12f"},{id: "12F"},{id: "13"}]
const itemToBeFound = {id: "12f"}

I'm trying to locate that item using a method like RegExp(/12f/i).test(string)

The reason for using the regexp is to make the search case insensitive. I'm aware that I could use toLowerCase or toUpperCase, but I'm curious about using this approach.

So I attempted

arr.find(({id}) => id == regexp)
in that direction. However, I haven't yet found a way to make it work.

Answer №1

To test the property, you just need to use a regular expression with the RegExp object

const items = [{
  id: "12f"
}, {
  id: "12F"
}, {
  id: "13"
}];
var pattern = new RegExp(/12f/i);
console.log(items.find(({id}) => /12f/i.test(id)))
console.log(items.filter(({id}) => /12f/i.test(id)))

Answer №2

When it comes to the current question parameters, this single line of code handles everything:

const matchedResults = array.filter((element) => (/[elementToBeMatched.id]/gi).test(element.id))

Answer №3

Utilizing the pattern and flags parameters of the RegExp object allows for dynamic comparison as shown below:

// Flexible Matching.
const customFilter = (array, criteria) => {
  const regex = new RegExp(criteria.id, 'i')
  return array.filter(item => regex.test(item.id))
}

// Example.
console.log('12f', customFilter([{id: "12f"},{id: "12F"},{id: "13"}], {id: "12f"}))
console.log('13', customFilter([{id: "12f"},{id: "12F"},{id: "13"}], {id: "13"}))

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

Establishing relationships with Sequelize between tables in different schemas

Currently, I am working on a project that involves using Sequelize and PostgreSQL as the database. In this project, I have implemented dynamic schema creation whenever a new user registers on the website. Specifically, I have a table called user_credentia ...

Transform or retrieve information from input into unformatted text

I'm working on a JavaScript function that can convert input values to text. However, I am facing an issue as I only want to convert data from one specific row into plain text. Each row in my table has 5 cells along with a button for saving the data. I ...

Add a new module to your project without having to rely on the initial

I'm looking to experiment with a module by making some adjustments for testing purposes. You can find the code here. Currently, all I need to do is type "npm install angular2-grid" in my terminal to add it to my project. Here's my concern: If ...

Issues with displaying output in C++ arrays

Being relatively new to C++, I acknowledge this question may appear quite basic (or even dumb!). My goal is to return an array of (int i, int j) representing a position or coordinates. Below is the code I've been working on: int* PositionCalculator(i ...

There was a problem retrieving the product information from the API

I have been struggling to pinpoint the exact issue at hand. The foundation of HTML and CSS is pre-written, with JavaScript responsible for generating the core elements to populate the DOM. Within my script, I am attempting to retrieve product data in ord ...

A solution for accessing computed properties within a v-for loop

Currently, I am facing a challenge with the code provided below. It seems that computed properties do not support parameters. Do you happen to have any suggestions on how to overcome this issue? I am considering using watchers on functions but I am also ...

Dealing with a Node and Express server can be tricky, especially when trying to proxy a POST request along with parameters. You might encounter the error

I am trying to forward all requests made to /api/ from my local node server to a remote server, while also adding some authentication parameters to them. Everything works smoothly for GET requests with query parameters and POST requests without specifying ...

Updating a calendar page in Rails 4 using AJAX technology

Currently, I am utilizing jQuery's datepicker functionality to display a calendar. The intended behavior is that upon clicking on a specific date, the page should generate relevant information (in this case, a table showcasing available seating) assoc ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Empty POST request detected in select2 form submission

Looking for some assistance to help steer me in the right direction. My professor is unable to provide guidance. I'm currently struggling with handling POST requests in my form for select2 multiple fields. The issue arises from a Yes/No flag that dete ...

How can I create a new div element for every item in an array by utilizing JSX?

I am currently working on creating a div element for each item in an array using reactjs JSX. I wasn't sure how to tackle this, so I attempted the following approach: {results.map((element, index) => ( <div key={index} className={ ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...

Total number of requests made since the previous reset

I'm currently working on developing an API and I need to set up a route like api/v1/status in order to check the server status. This route should return a JSON response with the total number of requests made to the API since it became active. However, ...

In order for Angular forms to be considered valid, they must fall into one of two form

I am attempting to create a dynamic angular form where the user must enter either A or B. A represents a unique identifier, while B consists of a set of values that correspond to that identifier. My goal is to validate the form as valid if either A is ente ...

Creating hierarchical TreeNode structure in TypeScript

As I work with a flat one-dimensional array of type TreeNode (view interface definition below), my goal is to recursively traverse the array and add subsequent array elements as children. While attempting a non-recursive approach using a buffer, I encount ...

Creating stunning visuals with the power of SVG

I need to create a graphics editor similar to Paint using SVG for a school project. I have JavaScript code for drawing shapes like circles and lines, but when I try to add them to an onClick function for a button, it doesn't seem to be working. funct ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

Uncover the reason behind the application's crash with Titanium

If we encounter non-crashing errors, utilizing LogCatcher can help by pinpointing which Javascript code is causing the issue. However, in the event of a crash, there's no time for logging Javascript errors. In such cases, integrating tools like ARCA ...

react-query: QueryOptions not functioning as expected when utilizing userQueries()

When passing certain "query options" while using useQueries() to fetch multiple queries simultaneously, these specified "query options" do not get applied during query executions (e.g. refetchOnWindowFocus has a value of true but I want it to be false). F ...