What is the best way to sift through an array and extract only the values that correspond with a user's input?

In my HTML file, I have an input field and a button element within the body section. Here is how they are structured:

<input type="text" name="searchBar" id="searchBar">
<button onclick="returnText()">Submit</button>

It's worth noting that clicking the button will trigger the 'returnText()' function.

Moreover, the HTML file connects to a JavaScript file that contains the following array:

const myData = [
{
    name: "John Miller",
    age: 33,
    location: "Chicago"
},

{
    name: "Jane Doe",
    age: 78,
    location: "Lansing"
},

{
    name: "Jamie Stevens",
    age: 21,
    location: "San Diego"
}
]

Currently, I am attempting to match user input with any string or number contained in one of the objects in the array, and then display the matched data. However, I'm encountering challenges in connecting these pieces effectively.

The code snippet I've been working on so far produces an empty array as the output, shown below:

function returnText() {
 let input = document.getElementById('searchBar').value.toLowerCase();
 let filteredNames = myData.filter(e => e.name === input);
 console.log(filteredNames);
 };

Answer №1

Ensure to convert the item's name property value to lowercase before performing any comparison.

const myData=[{name:"John Smith",age:25,location:"Boston"},{name:"Emily White",age:45,location:"Miami"},{name:"Sam Brown",age:30,location:"Seattle"}];

function filterNames() {
  let input = document.getElementById('searchBox').value.toLowerCase();
  let filteredResults = myData.filter(e => e.name.toLowerCase() === input);
  console.log(filteredResults);
};
<input type="text" name="searchBox" id="searchBox" value="Emily White">
<button onclick="filterNames()">Search</button>

In case you need to compare all properties, consider using Object.values to fetch all object property values and check if any value matches the input. This approach allows for flexibility by accommodating additional properties without impacting functionality.

const myData=[{name:"John Smith",age:25,location:"Boston"},{name:"Emily White",age:45,location:"Miami"},{name:"Sam Brown",age:30,location:"Seattle"}];

function filterNames() {
  let input = document.getElementById('searchBox').value.toLowerCase();
  let filteredResults = myData.filter(e => Object.values(e).map(e => String(e).toLowerCase()).some(e => e.includes(input)));
  console.log(filteredResults);
};
<input type="text" name="searchBox" id="searchBox" value="White">
<button onclick="filterNames()">Search</button>

Answer №2

Is this the kind of solution you're looking for?

const data = [{name:"John Miller",age:33,location:"Chicago"},{name:"Jane Doe",age:78,location:"Lansing"},{name:"Jamie Stevens",age:21,location:"San Diego"]];

function retrieveData() {
 let input = document.getElementById('searchBar').value.toLowerCase();

 let filteredResults = data.filter((element) => {
  return Object.values(element).some((value) => {
   return value.toString().toLowerCase().includes(input);
  });
 });

 console.log(filteredResults);
 };
<input type="text" name="searchBar" id="searchBar" value="John Miller">
<button onclick="retrieveData()">Search</button>

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

Personalized Design Incorporating Sections and Sidebars

I need the aside to be positioned on the right side and the section on the left side, both centered in the space. Feel free to check out this link <!DOCTYPE html> <html> <head> <style> #main { width: 800px; margin: 0 auto; } ...

Is there a problem with undefined values for dynamic inputs?

When I execute console.log($('#mat_code_' + counter - 1).val());, I receive an undefined value even though the inputs are empty. This is the code snippet : $('#m_table').on('click', '.check', function() { ...

What is the simplest method for finding the position of a child element in relation to its parent?

My HTML markup is structured similarly to this: <div id="parentElement"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div ...

Prevent unexpected page breaks in <tr> elements on Firefox (Could JavaScript be the solution?)

Wondering if there are any ways, possibly through JavaScript or CSS, to avoid having page breaks within <tr> elements specifically in Firefox. Given that FF does not yet fully support page-break-inside, I assume this might need to be addressed using ...

When using Lockdown.js with NPM, I encounter a blank file being returned

When using Lockdown.js for NPM, I encountered an issue where the command to generate the lockdown file resulted in an empty file. Here are the links for the dependencies: NPM lockdown git Here is a snippet from my package.json: { "name": "nw", "pri ...

Issue specifically with Android 6 WebView - jQuery 1.9.1 where a RangeError is thrown due to the call stack size being exceeded

An error message "Uncaught RangeError Maximum call stack size exceeded" is causing a web application to fail in the jQuery-1.9.1 extend() function, but strangely it only occurs on Android 6. The application runs smoothly on all other platforms such as Des ...

Output the contents of a nested object

After setting up a variable containing music library data... var library = { tracks: { t01: { id: "t01", name: "Code Monkey", artist: "Jonathan Coulton", album: "Thing a Week Three" }, t02: { id: " ...

Issue encountered with subscripted value that is not classified as an array, pointer, or vector

void create_game_grid(struct game_board *board, FILE *output) { int rows, cols; /* Allocate memory for the correct number of rows */ board->grid = malloc(sizeof(*board->grid) * (board->numRows + 4)); for (rows = 0 ...

Exploring the World of 3D Rotation with Three.js

I currently have 2 mesh objects - the Anchor and the Rod. The Anchor rotates around the z-axis, as shown in the image. The Rod is designed to only move backward and forwards. You can view the image here: . However, I am struggling to determine the matrix ...

How to Retrieve an Array of Objects from a .dat File in Java

I'm struggling with restoring an array of objects from a saved file.dat in my Java program. I want to convert them into an array of the same object to use in my program, but the current code isn't working as expected. public static void mai ...

Is it possible to identify the origin URL of a user using Javascript or AngularJS?

Is it possible to use Angular to detect the origin URL of a user visiting my website in order to perform specific operations later on? ...

Asynchronous operations and recursive functions in the world of Node.js

When working with express and mongoose, I frequently find myself needing to perform batch operations on collections. However, the typical approach involves callbacks in nodejs concurrency coding, which can be cumbersome. // given a collection C var i = 0 ...

Unacceptable response from AJAX function

My goal is to extract specific information from this ajax function, such as the thumbnail image and the owner of the image. It seems like the function is not recognizing data.images[i].imgurl and data.images[i].username. AJAX call in ajax.php require_o ...

Is there a way to confine a jquery script within the dimensions of the container div?

I have recently created a gallery with navigation buttons in jQuery. As a newcomer to jQuery, I wrote a small script that adjusts the margin of a div container by a fixed amount. The script is functioning properly, but it extends beyond the top and bottom ...

Swapping Out Models in Three.js: A Guide to Replacing Object3D Models

I'm attempting to swap out an object3D for a character model, while retaining all of its attributes like the position. var object = new THREE.Object3D( ); object = models.character[0].clone( ); object.position.set( 100, 230, 15 ); scene.add( object.sc ...

Tips for designing a multi-level dropdown navbar

I am currently facing an issue with designing a navbar. I am aiming for Multi-Level Dropdowns, but whenever I click on More Services, it automatically closes the main dropdown menu. I have experimented with various approaches, but none of them seem to be ...

SlickGrid checkbox formatter/editor experiencing issues with data consistency

Exploring the functionalities of SlickGrid'seditors/formatters, I delved into how these features could potentially alter the data object utilized for constructing the grid (as modifications within the table are usually reflected in the original data o ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

Dynamic item addition feature activated by button on contact form

I am looking to create a form that includes the standard name, phone, email fields as well as a dropdown for selecting products and a text box for inputting quantity. The unique aspect is allowing users to add multiple products (dropdown and quantity textb ...

What is the best way to delete a jQuery.bind event handler that has been created for an event

I have a div and I need to assign two scroll functions to it, but I also want to remove one of them after a certain condition is met. <div id="div1" class="mydivs"> something </div> <div id="div2">Some crap here</div> <script&g ...