JavaScript: The most efficient method for locating a Regular Expression within an Object's properties

Suppose I have a scenario where I need to validate if the words in an array exist in a dictionary and take certain actions accordingly. Here's a snippet of the code that achieves this:

let dictionary = {
   aaa : 'value1',
   bbb : 'value2',
   ccc : 'value3'
}

let wordsArr = ['dfjd', 'aaa', 'Bbb', 'dfjkd']

for (let word of wordsArr) {
   if (word in dictionary) {
      console.log(word, 'is in dictionary')
   }
}

Now, the requirement is to modify the if statement in such a way that it ignores the case while checking for the word in the dictionary.

An approach to achieve this could be by iterating through Object.keys(dictionary) with a regular expression test on each key.

let dictionary = {
   aaa : 'value1',
   bbb : 'value2',
   ccc : 'value3'
}

let wordsArr = ['dfjd', 'aaa', 'Bbb', 'dfjkd']

for (let word of wordsArr) {
   let re = new RegExp(word, 'i');
   for (key of Object.keys(dictionary)){
      if (re.test(key)) {
         console.log(word, 'is in dictionary')
      }
   }
}

However, there might be a more efficient method than looping through every key in the dictionary for every word in the array, such as leveraging the in operator or the .hasOwnProperty() method.

Answer №1

I'm seeking an if statement that can check if a word is in the dictionary while ignoring case sensitivity!

Instead of using regex for this purpose, which may lead to additional issues like proper escaping as highlighted here, a simple solution exists.

All you need to do is convert the word to lowercase first and then search for it in your dictionary containing lowercase keys:

const dictionary = {
   aaa : 'value1',
   bbb : 'value2',
   ccc : 'value3'
}

const wordsArr = ['dfjd', 'aaa', 'Bbb', 'dfjkd']

for (const word of wordsArr) {
   if (word.toLowerCase() in dictionary) {
//         ^^^^^^^^^^^^^^
      console.log(word, 'is present in the dictionary')
   }
}

Answer №2

To maintain a quick lookup time of O(1), follow these steps:

  • Ensure all words in the dictionary are stored in lowercase format
  • Convert the word you want to check using .toLowerCase() method (e.g., word.toLowerCase() in dictionary)

By doing this, the case information is disregarded, resulting in the same string that serves as the dictionary key.

However, if your goal is to match keys against a regular expression, you will need to iterate through all keys.

* It's worth noting that the process also applies to uppercase letters; however, using lowercase tends to be more visually appealing when displayed.

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

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Utilizing API to Save Images Directly from the Client Side

I am currently in the process of redesigning a website, specifically the Blog section which includes a featured image. I have been researching the best method for saving these images. After following a tutorial that utilized the file.mv() function from ei ...

Tips for indicating which content to display on template literals

Utilizing template literals to showcase some fetched data, I've successfully displayed all the necessary information on the frontend. However, certain content is hidden and meant to be toggleable. Yet, I'm struggling to figure out how to link eac ...

Discovering numbers within a JSON object and extracting them - a step-by-step guide

If I have a JSON object coming from a random dataset and want to search through it to manipulate the number values, how can I achieve this? Looping through the object using for...of allows me to get the keys, but I'm unsure how to access every key-val ...

Navigating Angular's Resolve Scope Challenges

As a junior developer, I've been diving into Angular.js and exploring the resolve feature of the route provider to preload my Project data from a service before the page loads. Previously, I was fetching the data directly inside the controller. Howeve ...

What is the best way to stop div animations when clicking with jQuery?

Upon loading the page, a div animates automatically. There is also a button present. When the button is clicked, I would like to create a new div and animate it the same way as the first one. However, when this happens, the position of the first div also ...

"Enhance your website with a sleek Bootstrap navigation system featuring dividers and

Need help with creating a Bootstrap nav menu similar to this design made in Photoshop? Wondering about the best way to position the logo and create dividers between menu items like shown in this image. Here's the HTML code currently being used: & ...

When I expand the accordion next to it, the accordion disappears, and it also vanishes when I close that accordion

After incorporating accordions into my site, I encountered a peculiar issue (as shown in this video): when I open one accordion, the adjacent accordion also opens unexpectedly. Similarly, closing one accordion causes its neighboring accordion to mysterious ...

What steps should I take to address and resolve this problem with my Angular $scope?

One of my partials utilizes a single controller named CaseNotesCtrl. However, I am encountering difficulties accessing $scope variables within this partial. Below is the code snippet: <div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotes ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

My CSS files are not being included by grunt-bower-install

As someone who is relatively new to bower and grunt, I'm struggling with some basic tasks. After running bower install --save bootstrap, my goal is to use grunt-bower-install to update my js & css files as per the instructions on their documentat ...

Is there a solution to fix the issue with IE causing hover effects not to

I'm currently in the process of designing a website, and I have implemented some image hover effects that reveal elements within the image when you hover over it. These effects are functioning correctly on Chrome, Safari, and Firefox; however, they ar ...

"Enhance your Angular experience with SweetAlert integration using directives and translation

Currently, I am utilizing the Angular implementation of the SweetAlert plugin from GitHub. I am attempting to pass an Angular directive with translation to the title. The variable being passed as the title is: {{ 'register.confirmation_modal.SUPERI ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

Utilizing variable query operators solely in instances where they hold value

Imagine you are on a movie website where you can customize filters for the movies displayed to you. Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like: preferences: { yea ...

Displaying Vue v-for data in console.log

One interesting issue arises when printing a list in HTML and checking the output in HTML versus in console.log. It seems that the output is duplicated in the console. After some investigation, I made the following observations: Not showing the product ...

The Vuetify Jest button trigger fails to function properly despite utilizing a spy

Recently delved into the world of Vue.js and Jest to see how they interact. I watched some tutorials and then decided to give it a go myself, but ran into trouble with getting the trigger click to work. Within my component, I have a login button, which is ...

JQuery Mobile fails to apply consistent styling to user input check items within a list

I have successfully implemented the functionality to add user input items to a checklist. However, I am facing an issue where the newly added items are not adhering to Jquery Mobile's styling. Here is a screenshot showcasing the problem: Below is th ...

Ways to repair the error message: "Unable to access property 'clientWidth' of undefined"

Whenever I resize the window, I encounter an error stating "Cannot read property 'clientWidth' of null". It appears to be related to the fact that the ref is null. Do you have any suggestions on how to troubleshoot this issue? import React, { us ...