pair each instance of a string

Currently, I am developing a todo list application that allows users to add to-do list items and search for specific tasks. My focus at the moment is on refining the search function. Presently, whenever a user searches for a name, only the first task associated with that person is displayed. However, the challenge lies in displaying all tasks related to that individual, as they may have multiple assignments. For example, if Bob has three different tasks, the current search functionality will only show the first one, whereas I aim to showcase all three. Does anyone have any suggestions or ideas on how to accomplish this?

function search() {
   var searchTerm = document.getElementById("search").value;
   searchTerm = searchTerm.trim();

   if(searchTerm == null || searchTerm == "") {
   alert("Please enter a string to search for");
   return;
   }
   else {
     var todoObj = undefined;
     results = undefined;
     re = undefined;

   for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
       var ul = document.getElementById("test");
       var li = document.createElement(li);
       li.className = "listItem";  
       li.innerHTML = "You found " + todoObj.who + " who needs to " + todoObj.task; 
       ul.appendChild(li);    
       }
      }      
     }    
    }

Answer №1

Create a temporary list to store the matching todos, then display the results at the end:

var matchedTodos = []; // temporary list for matches

for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
         // add matching todo to temporary list
         matchedTodos.push(todoObj);
     }
 } 

// display the matched todos

if (matchedTodos.length > 0) {
    var ul = document.getElementById("test");
    var li = document.createElement("li");
    li.className = "listItem";  
    var tasks = '';
    var todoObj = null;
    for(var j = 0; j < matchedTodos.length; j++) {
        todoObj = matchedTodos[j];
        tasks += todoObj.task + ', ';
    }
    li.innerHTML = "You found " + todoObj.who + " who needs to " + tasks.trimEnd(', '); 
    ul.appendChild(li);  
}

The desired output should resemble something similar to

"You found Bob who needs to clean his room, take a bath, sleep"
. Ensure proper logic is added to handle the correct number of commas in the sentence.

Edit: To display each match as individual list items:

var matchedTodos = []; // temporary list for matches

for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
         // add matching todo to temporary list
         matchedTodos.push(todoObj);
     }
 } 

// display the matched todos

if (matchedTodos.length > 0) {
    var ul = document.getElementById("test");
    var todoObj = null;
    for(var j = 0; j < matchedTodos.length; j++) {
        var li = document.createElement("li");
        li.className = "listItem";  
        todoObj = matchedTodos[j];
        li.innerHTML = "You found " + todoObj.who + " who needs to " + todoObj.task;
        ul.appendChild(li);  
    } 
}

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

My React application is being loaded by Express regardless of the route I access. What could be causing this issue?

I'm struggling to access the json data located at /species because express always seems to load the react app regardless of the route I use. Can someone help me identify the issue? Here is an excerpt from my server.js file: const app = require(' ...

Prevent the page from refreshing when a value is entered

I currently have a table embedded within an HTML form that serves multiple purposes. The first column in the table displays data retrieved from a web server, while the second column allows for modifying the values before submitting them back to the server. ...

Customize Date Display in Material-UI DataGrid

How do I change the date format in MUI DataGrid from mongo's format to moment.js? In addition, I would like to add a new field with an edit icon that, when clicked, will redirect to the edit page. Here is what my code looks like: const columns = [ ...

Issue: Unable to reach essential Node.js modules

After attempting to deploy Next.js on Cloudflare Pages, I encountered the following error: Error: Could not access built-in Node.js modules. It is recommended to ensure that your Cloudflare Pages project has the 'nodejs_compat' compatibility flag ...

Retrieving multiple images from a directory and storing the image filenames in a JSON array

Currently, I am attempting to locate and retrieve the images stored within a specific folder using the following code. This code successfully retrieves the image names along with the total count of images. Subsequently, my goal is to save this information ...

Choose All Box for Dynamic Tables in AngularJS

Hi everyone, I'm currently working on adding a select-all checkbox to the top of my list of checkboxes using a custom directive. I found some guidance on how to do this in a thread that I came across: https://github.com/lorenzofox3/Smart-Table/issues/ ...

Vite and Transloadit encountered a type error: Unable to access properties of undefined when trying to read 'Resolver'

Currently, I am developing a Vite application using Vue 3.x that involves interactions with images/PDFs through Transloadit. While working on creating my own plugin for Transloadit integration, I encountered some issues. Initially, I managed to resolve an ...

What is the best way to generate a new column in pandas by calculating the variance between two string columns?

Is there a way to add a new column in pandas that shows the difference between two existing columns containing strings? For example, I have a "Good Address" column with entries like "123 Fake Street Apt 101" and a "Bad Address" column with entrie ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

Vue is set up to monitor changes in two connected input fields for user input exclusively

Two input fields are available, where the value of one can affect the other. If a value between 1 and 200 is entered in the level field, Vue will look up the corresponding points for that level and populate the points field with them. Conversely, if a us ...

Error encountered when attempting to pass a custom component as a prop in VueJS that is undefined

Can you please clarify why Vue is indicating that Unknown custom element: <MyComponent> - did you register the component correctly? is an issue in this code snippet: const CustomComponent = Vue.component('CustomComponent', { template: &a ...

The onClick event in React/NextJS is not functioning properly when applied to an external component

One dilemma I am facing involves my main page and a button component that I have created to be reused throughout my project. Strangely, when I add the onClick event to the external component, the click event does not seem to work. However, if I create the ...

Create a custom hook that encapsulates the useQuery function from tRPC and provides accurate TypeScript typings

I have integrated tRPC into a project that already has API calls, and I am looking to create a separate wrapper for the useQuery function. However, I am facing challenges in getting the TypeScript types right for this customization. My Objective This is w ...

Display various components using a dropdown selection

I am seeking guidance on how to display different components based on the selected option. I am unsure of how to write the code for displaying either component one or two. Can you provide any examples or references that may help? <template> <div ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

What is the best way to eliminate all click event handlers with jQuery?

I'm encountering an issue where multiple click events are being attached to a button. Specifically, when a user clicks on an 'Edit' link, the following JQuery code is executed: $("#saveBtn").click(function () { saveQuestion(id); }); Ea ...

JavaScript problem indicating an error that is not a function

Recently, I've delved into the world of JavaScript and am currently exploring JavaScript patterns. I grasp the concepts well but struggle with calling functions that are already in an object. var productValues = 0; var cart = function(){ this. ...

The 'Cross domain jQuery Ajax request using JSONP' triggered an error: SyntaxError - Unexpected token : appeared on the screen

I've been struggling to extract information from the steam api, encountering persistent difficulties due to the error mentioned above. Below is the snippet of code I have been utilizing: var steamurl = "https://api.steampowered.com/IDOTA2Match_570/Ge ...

Struggling to send an array through Ajax to Django view?

I am just starting to work with ajax and I want to pass an array from JavaScript to my view. Here is the template. I have a form that takes the course ID number and score from students, creates a table, and adds how many courses the student wants to add. ...

What methods can be used to send JSON data in the body of an express router.get request?

I am currently working on setting up an express endpoint to fetch data from an API and return the JSON response in the body. We are receiving JSON data from a rest API as an array and my goal is to utilize express router.get to present this formatted JSON ...