A guide to sorting an array based on user input using Javascript

I have developed an app that utilizes JavaScript and the VueJS framework. I am currently working on implementing a 'dropdown' feature for items that are dynamically filtered based on user input.

Below is the code snippet responsible for rendering the list on the page:

<div>
    <v-list v-for="item in userInputedFormulas" :key="item.id" >
        <v-list-item>
            <v-list-item-title>
                {{ item.name }} {{ item.structure }}
            </v-list-item-title>
        </v-list-item>
    </v-list>
</div>

The method used to generate userInputedFormulas is shown below:

userInputedFormulas() {
    this.userInput.forEach(element => {
        if(this.allFormulas?.filter(formula => formula.name.includes(element.toLowerCase()))) {
            filteredList = this.allFormulas?.filter( 
                formula => formula.name.includes(this.userInput)
            );
        } if(this.userInput == this.allFormulas?.filter(formula => formula.name)) {
            filteredList = this.allFormulas?.filter(formula => formula.name = this.userInput)
        }
    });
    return filteredList;
}

It's important to note that allFormulas returns an array of objects containing various formulas like: [{name: 'SUM', structure: 'blah'},{name: 'ADD', structure: 'blah'},{name: 'MINUS', structure: 'blah'}]

The current functionality allows for filtering as the user types, as demonstrated in the following screenshot:

https://i.sstatic.net/1w1hL.png

However, there is a specific scenario where I want to refine the filter using characters such as ( (round opening bracket) to display only the exact formula.

For instance, if the user inputs 'SUM(' instead of displaying all items with 'SUM' in the name as shown above, it should only display the 'SUM' item. How can I achieve this specific filtering requirement as I'm unsure about the approach?

Answer №1

Is it possible to utilize a regular expression to match the search query, and then if a round opening bracket is found, switch the operation from filtering an array to locating the exact item?

Answer №2

There are two possible solutions that I can see:

Option A: If your regex pattern is currently written as ^(TERM)/gm, you could modify it to ^(TERM)$/gm by replacing the opening bracket with a dollar sign. This modification will ensure that the regex evaluates the entire term instead of just parts of it when a user inputs a (.

Option B: Alternatively, a cleaner approach would be to create specific regex patterns for each result item and use them to evaluate the search term individually. For example, you could define a regex like this for the SUM function: ^SUM(\(([\d,\s]+\))?)?/gm (Please note that I am not an expert in regex).

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

Tips on running jQuery scripts when a div changes its display style from none to block?

Is there a way to trigger jQuery code when the style of a div transitions from `display: none;` to `display: block;`? I am working with tabs, which is why this div's style changes in this manner. The jQuery code should only be executed when this spec ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

Creating a "return" button for an editing form in AngularJS Datatables with the help of a form directive

Using AngularJS Datatables, I implemented a grid with additional "edit" and "delete" buttons in the last column. How is the grid/table rendered? HTML <!-- Required CSS and JS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/li ...

The display of options in React Bootstrap typeahead is not functioning properly

When I try to implement React Bootstrap Typeahead, the options do not appear in the Typeahead component upon page load. Here is a snippet of my code: const React = require('react'); ... (code continues) The options are generated as follows: [ ...

Tips for reactivating a disabled mouseover event in jQuery

I created an input field with a hover effect that reveals an edit button upon mouseover. After clicking the button, I disabled the hover event using jQuery. However, I am unable to re-enable this hover event by clicking the same button. Here is the code s ...

New to JavaScript and Bootstrap - eager to learn by using Bootstrap 4 Chart Template, just need help with a small issue in the code

I am eager to dive into Bootstrap 4 and data visualization charts. I want to replicate the visualizations found in the link below. However, after copying and pasting the code into Atom, it's not functioning as expected. I ensured that I copied the HT ...

Exploring Javascript/JQuery parameters based on data types

I'm a bit confused about whether the title accurately reflects my question. I need help understanding how jQuery deals with functions that are called with different argument combinations, such as ("Some String", true, function(){}) and ("Some String", ...

Retrieve the outcome of a mongoose query within a designated function

Seeking help with returning a result from my mongoose find operation. While similar questions have been asked before, this one is unique. Here's an example of my user: let UserSchema = new mongoose.Schema({ variable: {type: mongoose.Schema.Object ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

Can pins be added or removed from a location plan (image or vector) using either Javascript or the DevExpress library?

At the factory where I am employed, there are close to 1000 cameras in operation. I have requested to have the locations of these cameras marked on a non-geographical map of the factory. By simply clicking on one of the camera icons, it should be possible ...

Only dispatch to props upon being clicked

I am encountering an issue with the mapDispatchToProps function being sent as a whole, rather than only when I click on the delete button. My class successfully fetches the list data and everything works as expected. However, upon adding the delete button ...

Steps to creating a nested function

I'm still learning the ropes of Javascript, and I've been working on creating a personal library to streamline my coding process. Here's the code snippet I've come up with. function myLibrary() { let _this = this; this.addString = ...

What is the fewest amount of commands needed to generate a client-side Javascript code that is ready for use?

In the realm of JavaScript libraries found on Github, it has become increasingly challenging to integrate them directly into client-side projects with a simple script tag: <script src="thelibrary.js"></script> The issue arises from the browse ...

I am looking to transfer an image stored in a database onto a card

One issue I am facing is that when trying to display an image from a database, uploaded by a user and showing on a card with additional information like name and price, an icon resembling a paper with green appears in the output. Here's my code snippe ...

Iframe form submissions

I am interested in accomplishing the following task. My objective is to submit a form to my booking engine and show the results on either a new page or within a Div element. Ideally, when the user clicks the submit button, it would display an Iframe or re ...

The Ajax request returned a status of 200, yet an error message was displayed

Even though the status is 200, why does it print the error message inside alert("error...");? function makeSelect() { var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value; var url = "http://dukano.co/sakh ...

The Module Design Pattern in Jquery

In my project, there is a jQuery module pattern that I am having trouble understanding its purpose. There is also a custom plugin called jquery.skInit.js (function($) { $.fn.skInit = function() { return this.each(function(i,element) { var e = ...

What is the best way to apply various styles using the ng-style directive in different scenarios?

When working in Angular, I am attempting to apply different style attributes based on varying conditions. However, the typical conditional expression method is limited to just two conditions and is not providing the desired results. <div ng-style=" ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

Adding a new property to a reactive object in VueJS 3: A simple guide

export default { setup() { const imageUrl = ref(""); const title = ref(""); const description = ref(""); var source = "Global"; const form = reactive({ title: "", descript ...