Using optional chaining along with the methods toLowerCase and indexOf while iterating through an array using the map

I have implemented an autocomplete input that searches for project properties while typing. I am looking to enhance the existing code for better performance.

filterProjects(value: string) {
  return this.projects.filter(
    project =>
      project.key.toLowerCase().indexOf(value.toLowerCase().trim()) >=
        0 ||
      project.name.toLowerCase().indexOf(value.toLowerCase().trim()) >=
        0 ||
      project.description?.toLowerCase().indexOf(value.toLowerCase().trim()) >=
        0
  );
}

and replacing it with the following code:

filterProjects(value: string) {
  return this.projects.filter(project =>
    [project.key, project.name, project.description].map(
      str => str?.toLowerCase().indexOf(value.toLowerCase().trim()) >= 0
    )
  );
}

I decided to use optional chaining because the description field can sometimes be null or undefined.

However, I am facing an issue where the function returns the array unmodified. Additionally, when the value is found in the description of one item, the array is not filtered to just that specific item.

Is there a solution apart from resorting to traditional checks like if (str !== undefined)? Let me know your thoughts.

Answer №1

It's important to note that the map function returns an array of booleans, which will always be truthy regardless of the data. If you are searching for a specific condition within an array, you should use the Array.some method (also available in lodash/underscore/ramda for compatibility with older browsers). Additionally, you can modify the inner predicate like this:

filterProjects(value: string) {
  return this.projects.filter(project =>
    [project.key, project.name, project.description].some(str =>
      str ? str.toLowerCase().includes(value.toLowerCase().trim()) : false
    )
  );
}

Answer №2

One helpful technique is utilizing the 'Nullish coalescing operator (??)'

similar to

str => (str ?? "").toLowerCase().indexOf(value.toLowerCase().trim()) >= 0

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

Issues with parsing application/json data in NodeJS using Express

As a newcomer to setting up a NodeJS express JSON REST API, I am encountering challenges in retrieving the JSON data from both GET and POST requests. Here is the code snippet that I am currently working with: var bodyParser = require("body-parser"); con ...

Refreshing the private route redirects the user to the login page

Currently, I am working on setting up a private route within my React app. I have integrated Redux and Redux-Toolkit (RTK) Query for handling state management and data fetching. The issue I am facing is that whenever I reload the private page, it redirects ...

Issue with setting value using setState in TypeScript - what's the problem?

Every time I attempt to update the value of currentRole, it appears highlighted in red. Here is a screenshot for reference: const Container: React.FC<ContainerProps> = ({ children }) => { const [role, setRole] = useState<string>(); useE ...

Can you convert a preprocessor to an array?

Can a preprocessor be cast to an array? This question arises as I attempt to convert a preprocessor to an array. Specifically, I am uncertain about the feasibility of this task, given the preprocessor defined as Number 0x44332211. Below is the code snipp ...

What is the best way to replicate touch functionality on mobile browsers for both Android and iPhone devices?

Recently, while developing a web application, I ran into an issue on mobile browsers where the :active pseudo class wasn't functioning properly. I am currently utilizing CSS sprites and looking for guidance on how to simulate clicks for mobile browser ...

The toolbar button in the Froala WYSIWYG editor is mysteriously missing from view

Embarking on a project with Froala editor and Angular 1, I meticulously followed the documentation to show the insertImage button and insertTable, but they are not appearing. Here is my code: var tb = ["bold", "italic", "insertTable", "insertImage"]; $sc ...

Moving the panel to follow the mouse cursor in Firefox Add-on SDK

Is there a way to show a panel on the screen at the exact position of the mouse? I'm finding it difficult to understand how to change the position of the panel in Firefox SDK, as the documentation lacks detailed information. ...

Creating a ROT13 cipher in JavaScript

In my JS function, I need to handle a variable called i. My goal is to encode this variable using ROT13 before proceeding with the function. The challenge lies in decoding the variable and integrating it into the script. I came across a JavaScript implem ...

Possible rewrite: "Unable to use jQuery to add elements to data fetched through AJAX requests."

I am looking to add a button to copy code inside every div that has a class starting with language. The code is functioning properly, however, after attempting to retrieve data from the database using Ajax, the button no longer appears in the div as it did ...

What is the optimal method for updating the values of an unordered_map array for a particular key efficiently?

Review the following examples of unordered maps: #include <array> #include <string> #include <unordered_map> int main() { std::unordered_map<std::string, int> str2int { {"key1", 1}, {"key2", ...

How to Retrieve the Order Number of an Object in an Array using JavaScript ES6

Curious about JavaScript ES6 and needing assistance! I have a simple question - how can I determine the order number of an object in an array? [ { "pk": 23, "image": "http://localhost:8000/media/users/1/2_27.jpg"}, { "pk": 11, "image": "http://localho ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Discovering the kth largest number in two arrays that are sorted and have varying sizes

This question is different from An algorithm to find the nth largest number in two arrays of size n because the two sorted arrays have different sizes. I attempted to apply a modified version of the algorithm proposed to solve my specific issue, but I am ...

Customizing the text color of words that originated from a dropdown selection within an Angular textarea editor

My Process: Within my interface, I utilize both a dropdown menu and a textarea field. I input text into the textarea and select certain words from the dropdown menu to add to the textarea. I have successfully completed this task. The Issue at Hand: Now, ...

Obtain individual information from XML

After fetching data from the server using ajax, I am looking to retrieve only a specific part of the data which is the name. How can I modify my code to achieve this? const url = 'https://jsonplaceholder.typicode.com/users' const xhr = new XMLH ...

Using the clientWidth property in React

While I have a solid background in Javascript, I am relatively new to working with React. In my previous projects where I coded directly in javascript for the browser, I frequently used the following code snippet: width = document.getElementById('elem ...

Modifying the position of an HTML element within its parent tag using document.createElement

As I dive into learning Javascript, I've come across document.createElement. This method allows me to create an HTML tag and insert it into an existing HTML parent element. However, I have a specific question in mind: Is it possible to choose the exac ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

Error encountered when attempting to use explode() with text files, resulting in an undefined

I am currently working on extracting data from a text file called itest.txt, which contains a list of 100,000 numbers, each number on a separate line. When I viewed the contents of $contents, I noticed that it is a string type with all the numbers separat ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...