Arranging Words in Search Boxes Through JavaScript

Inquiry. As a beginner in VueJS and JavaScript, I am currently working on setting up a search bar. While it functions properly, I am facing a challenge. I wish to enable the search functionality to look through an object's description even if the input words are not in the correct sequence.

Illustration. For instance, if the description string is "Gucci blue belt" and I type "Gucci blue" in the search bar, the result displays as expected since the description contains the words in that order. I aim to implement a feature where typing "Gucci belt" will also show the item with the description "Gucci blue belt."

The current computed code in VueJS section

filteredsortedobjects (){
    return this.sortedobjects.filter(object => {
        var Objectslist_n = object.name;
        var Objectslist_q = object.quantity;
        var Objectslist_c = object.category;
        var Objectslist_s = object.section;
        var Objectslist_d = object.description;
        var Objectslist_date = object.reception_date;
        var Input = this.searchQuery;

        /* Create arrays with all information in the table */

        var Objectslist_nq = Objectslist_n.concat(Objectslist_q);
        var Objectslist_nqc = Objectslist_nq.concat(Objectslist_c);
        var Objectslist_nqcs = Objectslist_nqc.concat(Objectslist_s);
        var Objectslist_nqcsd = Objectslist_nqcs.concat(Objectslist_d);
        var Objectslist_nqcsddate = Objectslist_nqcsd.concat(Objectslist_date);

        /* Filtered variables */

        var F_Objectslist = RemoveAccents(Objectslist_nqcsddate.toLowerCase());
        var F_Input = RemoveAccents(this.searchQuery.toLowerCase());

        /* Function to remove accents */

        function RemoveAccents(str) {
            var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
            var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
            str = str.split('');
            var strLen = str.length;
            var i, x;
            for (i = 0; i < strLen; i++) {
                if ((x = accents.indexOf(str[i])) != -1) {
                    str[i] = accentsOut[x];
                }
            }
            return str.join('');
        };
        console.log(F_Objectslist);
        console.log(F_Input);
        return F_Objectslist.includes(F_Input)
    })
}

I acknowledge that the accent removal function has not been implemented while conducting tests.

Attempted Approach. To address this concern, I have attempted converting variable F_Input (search bar input) and F_Objectslist (an array containing all item details such as names, categories, sections, quantities, descriptions, and dates) into strings using array.split(" "). This resulted in arrays of strings ["word", "word2", ...] for both variables in the console.

At this stage, I am uncertain about how to verify if the strings within my F_Input array exist in the F_Objectslist array regardless of their order.

Thank you for your assistance!

Answer №1

To begin, separate the F_Input variable by spaces and then utilize 'Array.prototype.map()' to iterate through the array of search terms in F_Input using the current approach.

It's important to note that all these actions are linked together with a final invocation of the .every() method. The last step ensures that every search operation (via map) must yield a true result (or an array filled entirely with the value true);

const F_Objectslist = "this is search term, and this is term search".split(' ');
const F_Input = "search term";

let result = search(F_Objectslist, F_Input);
console.log(result);

let notFoundResult = search(F_Objectslist, "search dog");
console.log(notFoundResult);

function search(text, terms) {
  return terms.split(' ').map(term =>text.includes(term)).every(found=>found===true);
}

Answer №2

In my opinion, you were almost there with your approach. Here's how I would tackle it:

function searchForMatch(input, match) {
  let isMatch = true;

  const matchArray = match.split(' ');
  const inputArray = input.split(' ');

  inputArray.forEach(word => {
    if (matchArray.indexOf(word) === -1) {
        isMatch = false;
    }
  });

  return isMatch;
}

You can test the functionality in this working fiddle

Answer №3

Here is the answer I came up with.

I successfully created a highly responsive search bar that can search for information within an array! For those interested, here is the code!

Inside page.vue under computed

 filteredsortedobjects (){
    return this.sortedobjects.filter(object => {
      var Objectslist_n = "a" + object.name;
      var Objectslist_c = object.category;
      var Objectslist_s = object.section;
      var Objectslist_q = object.quantity;
      var Objectslist_d = object.description;
      var Objectslist_date = object.reception_date;
      var Input = this.searchQuery;

      /* Form arrays with all table information */

      var Objectslist_nc = Objectslist_n + " " + Objectslist_c;
      var Objectslist_ncs = Objectslist_nc + " " + Objectslist_s;
      var Objectslist_ncsq = Objectslist_ncs + " " + Objectslist_q;
      var Objectslist_ncsqd = Objectslist_ncsq + " " + Objectslist_d;
      var Objectslist_ncsqddate = Objectslist_ncsqd + " " + Objectslist_date;

      /* Filtered variables */

      var F_Objectslist = RemoveAccents(Objectslist_ncsqddate.toLowerCase()).split(" ") + " ";
      var F_Input = RemoveAccents(this.searchQuery.toLowerCase()).split(" ");

      /* Function to remove accents */

      function RemoveAccents(str) {
        var accents    = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
        var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
        str = str.split('');
        var strLen = str.length;
        var i, x;
        for (i = 0; i < strLen; i++) {
          if ((x = accents.indexOf(str[i])) != -1) {
            str[i] = accentsOut[x];
          }
        }
        return str.join('');
      };

      return F_Input.every(object => {
          if (F_Objectslist.indexOf(object) === -1) {
          }
          else {
            return F_Objectslist.indexOf(object)
          }
      })

    })
  }

I have included an input with the attribute v-model="searchQuery". Also, there is a table that displays

   <tr id="tr" v-for="object in filteredsortedobjects" v-bind:key="object.name">
    <td>
      <p>{{ object.name }}</p>
    </td>
    <td>
      <p>{{ object.category }}</p>
    </td>
    <td>
      <p>{{ object.section }}</p>
    </td>
    <td>
      <p>{{ object.quantity }}</p>
    </td>
    <td>
      <p>{{ object.description }}</p>
    </td>
    <td>
      <p>{{ object.reception_date }}</p>
    </td>
  </tr>

The object.something are imported from a JSON file using

<script>
import objects from "./Database/Objects.json";
</script>

You may need to set some data information in the data() section

searchQuery: ""

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

Is it possible to use a variable for the value attribute in a select option?

In a mongodb database, I have a collection that stores "username" and "email". Now, I am trying to create a webpage on a localhost server where I can display the username and email of a specific user based on a selection from a drop down menu. I have succe ...

What is the best way to utilize AJAX for extracting all the "name" values from my JSON data?

There is a JSON file containing nine complete record sets, but I will share three of them below. My ultimate goal is to implement AJAX on a website. Currently, the information from the JSON file is hardcoded into the HTML. However, I have extracted and or ...

Dynamic header that adjusts to fit window size fluctuations

I'm currently working on a website and trying to make it responsive by adjusting to changes in the browser window size. I'm having trouble changing the header height based on the window size unlike how it works for my pictures in CSS: #l ...

Extracting information from a database (HTML, JavaScript)

I am currently working on a table that receives data from the server using ajax: $.each(data, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td>" +data[i].A+ "</td><td>" +d ...

`Unable to retrieve Shopify products using shopify-api-node`

I'm encountering a 403 error while trying to retrieve products from my custom Shopify app using the shopify-api-node module. Below is the code snippet I've put together based on a helpful discussion on Stackoverflow: const express = require(& ...

Identifying the selected element within a THREE.js object

I've created a sphere with a background image, and placed the camera inside to create a panoramic effect when the sphere rotates. Now I'm looking to detect when a user clicks on the sphere using a three.js example: var intersects = ray.intersec ...

The differences between using the opacity attribute in HTML and the opacity property

There are two distinct methods for adjusting opacity in HTML: <div opacity="0.5"></div> and <div style="opacity: 0.5;"></div> I am familiar with setting these values in JavaScript as well: div.setAttribute("opacity", 0.5); and ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

Transferring a variety of outcomes back from PHP using AJAX

Currently, I have set up an AJAX feature for testing purposes. The main idea behind this is to send data from dropdown boxes to a PHP script, perform calculations, and then return the result. While it successfully returns the result, I now aim to send back ...

Discovering the following element containing an ID attribute with jQuery

Upon clicking a link, my goal is to locate the subsequent <section> with an ID attribute and retrieve its ID. In the provided code snippet and JavaScript function, the expected outcome upon clicking the link is for "section_3" to be logged in the co ...

Steps for creating an effective page preloader

My website involves fetching data upon loading. I am working on implementing a preloader that will be displayed until the site fully loads and all initial requests are completed. I've come across tutorials for preloaders that rely on setting a time i ...

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

The function res.render is not displaying the new page

I have a task that seems straightforward. On my header, I am loading a few a links. <a class="nav-link" href="menu">Menu 1</a> I am attempting to access the URL /menu from this link. In my app.js file: app.use('/', index); app.us ...

Switching between three div elements along with two icons can be done by using toggle functionality

Is there a way to make the icon change back when clicked again without making major changes to the existing code? Looking for suggestions on how to achieve this functionality. function myFunction() { var element = document.getElementById("demo"); el ...

Is there a way to fix the issue of ContextMenu not appearing at the right position within a scrollable

I have a div within an iframe that needs to display a context menu when right-clicked. The div's length may exceed the visible area, making it scrollable. However, the issue I am facing is that the context menu appears in a different position than whe ...

Form with a dropdown menu and a button to duplicate the dropdown menu

In my form, I have a simple setup where user names are listed, and for each user, there is a drop-down box displaying items that can be assigned to them. To facilitate the assignment of multiple items to a user, I want to implement a feature where a "add a ...

Ways to add a CSS class to an ID that immediately follows

I've been working on an editable table using the HTML5 attribute contenteditable. Everything was going smoothly until I had an idea to highlight the cell that was just updated by adding a class called alert-danger from Bootstrap. Once a cell is succe ...

Unlock maximum screen viewing on your custom video player with these steps to activate fullscreen

I'm having an issue with my basic video player - when toggling fullscreen, it doesn't fill the whole screen even though I tried using .fullscreen{width:100%} without success after searching for a solution. html <div class='player-contai ...

Dispatch an email without pausing for the task to complete its execution

Trying to avoid the delay caused by sending an email before exiting the page. The application is performing a series of actions before exiting: Database interaction Sending Email (notifying a manager about the transaction) Exiting the page/application. ...

Oops! The API request was denied with error code 401 - Unauthorized in React

I have been working on incorporating an API into my front-end project using React/Typescript. The documentation for the API specifies that authorization requires a key named token with a corresponding value, which should be included in the header. To stor ...