Display all items that contain a specified string using JavaScript

I'm in need of some assistance with a problem that I've been struggling with. I have several JavaScript objects containing different data pieces as shown below:-

Object {id: 1, shopcounty: "cornwall", shopaddress: "the cycle centre,<br />1 new street,<br />penzance,<br />tr18 2lz<br />}
Object {id: 2, shopcounty: "cornwall", shopaddress: "heliport link road,<br />long rock,<br />bude,<br />tr18 3rg"}
Object {id: 3, shopcounty: "cornwall", shopaddress: "heliport link road,<br />long rock,<br />bude,<br />tr18 3rg"}
Object {id: 4, shopcounty: "cornwall", shopaddress: "west end cottage,<br />trescowe,<br />penzance,<br /&>tr20 9rn"}
Object {id: 5, shopcounty: "cornwall", shopaddress: "22 joannies watch,<br />saint ives,<br />tr26 2fr"} 

What I'd like to achieve is to take a user input value and search the address of each object for a matching string, then return all details if there's a match.

For instance, if a user types in "bude" as their location, objects 2 and 3 should be returned along with their respective data. However, my current code seems to just return true for every object. I've tried using methods like match() and indexOf(), but still end up with all objects being returned.

<input id="submit" type="submit" name="form-submit">
// user input:  "bude, united kingdom"

<script>

    $('#submit').on('click tap', function(e){
        e.preventDefault();

        var userInput = document.getElementById('user-location').value;

        for (var i = 0; i < bikeshops.length; i++) {    
            console.log(bikeshops[i]);

            if($.inArray(userInput, bikeshops[i])){

                // console.log(bikeshops[i].shopaddress);
                // returns everything!
            }           
        }           
    });
</script>

Answer №1

To implement this functionality, you can utilize the combination of Array.prototype.filter and String.prototype.indexOf. Here's how:

$('#submit').on('click tap', function(e){
    e.preventDefault();

    var userInput   = document.getElementById('user-location').value;

    var result = bikeshops.filter(function(o) {           // iterate through each object o in the array bikeshops
        return o.shopaddress.indexOf(userInput) !== -1;   // filter out objects with shopaddress property containing userInput
    });       

    console.log(result); // display only the objects matching the specified user input in their shopaddress property
});

Answer №2

Below is a functional resolution:

$('#click').on('click tap', function (e) {
  e.preventDefault();

  var input = $('#user-info').val();
  
  var places = [
    {id: 1, city: "new york", address: "123 main street,<br />new york city,<br />ny 10001<br />"},
    {id: 2, city: "chicago", address: "456 maple avenue,<br />chicago,<br />il 60611"},
    {id: 3, city: "los angeles", address: "789 oak parkway,<br />los angeles,<br />ca 90001"}
   ];

  for (var j = 0; j < places.length; j++) {    
    if (places[j].address.indexOf(input) !== -1) {
      console.log(places[j].city.toUpperCase() + " - " + places[j].address);
    }           
  }           
});
<input id="user-info" placeholder="Enter location...">
<input id="click" type="submit" name="submit-form">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №3

$('#search-trigger').on('click tap', function(e){
    e.preventDefault();

    let userQuery   = document.getElementById('user-search-term').value;
    //get array of search results based on user input
    let filteredResults = performSearch(userQuery, dataList); 

    
    let attributes = ['name','category'];

    //Generate HTML with the search results, you can modify it to be a <p> 
    createHtml(filteredResults, attributes, '#resultsList', 'div', 'section');

});



function performSearch(query, data){    
  return filteredData = data.filter((item)=>{
    return item.includes(query.trim());
  });  
}

function createHtml(dataArray, keys, id, tag, openingTag=''){
  let htmlContent = openingTag;
  dataArray.forEach((element)=>{
     let newElement = `<${tag}>`;
     keys.forEach((key)=>{
       newElement+=` ${element[key]}`;
     });
     newElement+=`</${tag}>`;
     htmlContent+=newElement;
  });
 if(openingTag!='') htmlContent+=`</${openingTag}>`; 
 $(id).html(htmlContent);
}

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

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

What is the best way to retrieve the ajax response using Ajax.Responders in prototype.js?

I am looking to retrieve the response of each Ajax call within the function below Ajax.Responders.register({ onCreate: function() { }, onComplete: function(transport) { }, onSuccess: function(transport) { }, }); ...

Issue: Connection Problem in React, Express, Axios

I've encountered an issue while attempting to host a website on an AWS EC2 instance using React, Express, and Axios. The specific problem I'm facing is the inability to make axios calls to the Express back-end that is running on the same instanc ...

Setting the locale in an extended datapipe in Angular 4: A step-by-step guide

I have created a custom pipe by extending the DataPipe Angular class. import { Pipe, PipeTransform } from '@angular/core'; import { DatePipe } from '@angular/common'; @Pipe({ name: 'dateTimeFormater' }) export class DateTi ...

Encountering problem when trying to upload several images at once using a single input in CodeIgniter with

I'm attempting to use CodeIgniter and AJAX to upload multiple images using a single input field. Here's the code I have so far: HTML: <input type="file" name="files[]" id="file" multiple /> AJAX: $("#addItems").on("submit",function(e) { ...

Utilizing NPM modules in the browser using Browserify for seamless integration

I'm attempting to utilize Browserify in order to make use of an npm package directly in the browser. The specific package I am trying to leverage can be found here Within my code, I have a fcs.js file: // Utilizing a Node.js core library var FCS = r ...

PHP code for adding values in an associative array based on keys

I am trying to calculate the total sum of an array while grouping them by their key values. Here is the array I am working with: Array ( [0] => Array ( [delivery_plan] => 80::2020/07 [additional_amount_usd] => ...

Is it possible to retrieve the HttpsError status from a Firebase function?

Within my firebase function, I deliberately throw an error with a specific status and message using the following code: throw new functions.https.HttpsError('permission-denied', 'Token does not match'); When I receive the server respo ...

Animating a child element while still keeping it within its parent's bounds

I have researched extensively for a solution and it seems that using position: relative; should resolve my issue. However, this method does not seem to work in my specific case. I am utilizing JQuery and AnimeJS. My goal is to achieve the Google ripple eff ...

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...

Deactivate the Aloha Editor's sidebar

I am struggling to disable the sidebar on the Aloha Editor. I have tried implementing the code below, but it doesn't seem to work for me: Aloha.settings = { sidebar: { disabled: true } }; When I add this code after calling aloha(), nothing changes ...

Display a sneak peek of the letter as you browse through the list

My List has been populated with data from my database. I am looking to display a letter preview when scrolling through the A-Ö list. How can I achieve this? Thank you. public class L extends BaseActivity { private ListView m_listView; private DB ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...

What is the best way to duplicate a 2D array (matrix) in Python using a C function, while also performing intensive computations, and then obtaining a new 2D array (matrix) in Python as the result

I am attempting to copy a 2D numpy array (matrix) in a C function and retrieve it back in Python in order to perform calculations on it in C to take advantage of its speed. To achieve this, I need the C function matrix_copy to return a 2D array or a pointe ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

Utilize JSON Arrays within a JSON structure when programming in Java

Within my Array list are integer values ranging from 2 to 6, and I am checking if each number is odd or even using the code snippet below: JSONObject outerObject = new JSONObject(); JSONArray outerArray = new JSONArray(); JSONObject [] innerObject = new J ...

What is the best way to minimize the number of requests sent in AngularJS?

Currently in my demo, each time a user types something into an input field, a request is sent to the server. However, I would like only one request to be fired. For example, if the user types "abc," it currently fires three requests. Is there a way for the ...

When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user cred ...