Comparing various object fields to a single input value in JavaScript

I have a challenge with filtering a large dataset of products based on user input values. Here is an example of my product dataset:

const products = [
  {id: 0, name: "Product1", brand: "Theraflu", itemCode: "THE110", price: 5.45},
  {id: 1, name: "Product2", brand: "Benadryl", itemCode: "BEN121", price: 7.05},
  {id: 2, name: "Product3", brand: "Listerine", itemCode: "LIS204", price: 4.55},
  {id: 3, name: "Product4", brand: "Tylenol", itemCode: "TYL116", price: 6.10},
];

I managed to filter the products using different fields in each product object like this:

const keys = ["name", "brand", "itemCode"];

const getFilteredProducts = (filterText) => {
  const newProducts = products.filter(product => keys.some(key => product[key].toLowerCase().includes(filterText.toLowerCase())));
  
  return newProducts;
}

console.log(getFilteredProducts("Tylenol"));

The problem arises when I try to combine different fields for filtering, such as:

console.log(getFilteredProducts("product4 Tylenol"));

Unfortunately, this returns an empty array. Is there a way to address this issue without modifying the current filtering functionality?

Answer №1

If you're looking to filter products based on multiple keywords in the filterText, you can try something like this:

const attributes = ["name", "brand", "itemCode"];

const getFilteredProducts = (filterText) => {
  const searchWords = filterText.split(" ");
  const filteredProducts = [];

  for (const word of searchWords) {
    filteredProducts.push(
      products.filter(product => attributes.some(attribute =>
        product[attribute].toLowerCase().includes(word.toLowerCase())
      ))
    );  
  }

  return [].concat(...filteredProducts).filter((value, index, self) => 
    self.findIndex((m) => m.id === value.id) === index
  );
}

console.log(getFilteredProducts("Tylenol Product3"));

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

Benefits of utilizing Boomerang library over Resource Timing API

In the midst of a project that incorporates Node.js on the back-end and Angular.js as the front-end, I am seeking ways to collect page load data for various application resources on different browsers. Initial statistics have been gathered using the Reso ...

React scroll not triggering class changes

In the function handleScroll, I am attempting to add a class of red when scrolling down to a specific limit, otherwise applying a class of blue. However, it seems that it is only entering the else statement and also logging undefined for e.target.scrollTop ...

Conceal a div element after redirecting to a different HTML page

I have a dilemma with my two HTML pages - index.html and register.html. I am trying to navigate from index.html to register.html, but I want to skip the select region step and go straight to the login page. Here's the code snippet I've been attem ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

The error message "express-validator - req.checkBody does not exist" indicates that the

After spending the last 2 hours trying to resolve this issue, I'm starting to feel frustrated. Essentially, I am attempting to validate a form input, but I keep encountering the following error message. TypeError: req.checkBody is not a function at ...

Combine multiple arrays of JSON objects into a single array while ensuring no duplicates

Trying to combine two JSON arrays into one without duplicates based on date. The jQuery extend() function isn't doing the trick, so looking for an alternative solution that avoids nested $.each statements due to potential large dataset size... [ ...

Top method for creating integration tests in React using Redux and Enzyme

Currently, I am working on setting up integration tests within my application. There are a few API calls that occur both when the component mounts and upon a button click. The response from these API calls is stored in the app's store, which then upd ...

When the state of the grandparent component is updated, the React list element vanishes in the grandchild component. Caution: It is important for each child in a list to have a unique

In my development project, I've crafted a functional component that is part of the sidebar. This component consists of 3 unique elements. ProductFilters - serves as the primary list component, fetching potential data filters from the server and offer ...

Tips for aligning the timer on a client's webpage with the server

What is the most effective method to synchronize the time displayed on a webpage with the server? My webpage requires that a countdown begins simultaneously for all users and ends at precisely the same time to avoid any user gaining a time advantage. Whi ...

Enhanced jQuery Embed Code validation for user input using a textarea

Currently, I am developing a website that allows users to input embed codes from popular platforms such as Twitter, YouTube, Instagram, Facebook, and so on. The embed code undergoes validation checks and is saved if it meets the criteria. However, when us ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

Show/Hide a row in a table with a text input based on the selected dropdown choice using Javascript

Can someone please assist me with this issue? When I choose Business/Corporate from the dropdown menu, the table row becomes visible as expected. However, when I switch back to Residential/Consumer, the row does not hide. My goal is to only display the row ...

What is the best way to manage the input mask?

I am working with an API that provides input masks based on country codes. My goal now is to create a function that will dynamically format the input as the user types. For instance, if the user selects country code +55 and I receive the mask (##)####-### ...

Verification of symmetrical file formatting

When dealing with three separate file upload inputs, the challenge is to ensure that the uploaded files are not duplicates. Additionally, if the user selects image format files (such as png, jpg, jpeg), they must select all three inputs in image format. On ...

Experiment with catching an exception on variable `v`

In my code, I am using a v-if statement to display an error message in HTML. <div id="error" v-if="showError">Error User or Password</div> data() { return { showError: false, };} When I change the value of showError ...

Where does the 'Execution Context Destroyed' error originate from in my code?

Currently, I am developing a program to extract forum responses for the online University where I am employed. While I have managed to successfully navigate to the relevant pages, I encountered an issue when trying to include scraping for the list of learn ...

text/x-handlebars always missing in action

I'm currently working on my first app and I'm facing an issue with displaying handlebars scripts in the browser. Below is the HTML code: <!doctype html> <html> <head> <title>Random Presents</title> ...

The Angular filter received an undefined value as the second parameter

Currently, I am facing an issue while trying to set up a search feature with a custom filter. It appears that the second parameter being sent to the filter is coming through as undefined. The objects being searched in this scenario are books, each with a g ...

Exploring nested optgroup functionality in React.js

Within my code, I am utilizing a nested optgroup: <select> <optgroup label="A"> <optgroup label="B"> <option>C</option> <option>D</option> <option>G</option> </optg ...

Encountered an issue while attempting npm install, with the error message "Error: Undefined variable standalone_static_library in binding.gyp" and node-sass chokidar error

I've been working on updating a Ruby on Rails and React project from 3 years ago. However, I encountered an issue while trying to npm install. $ npm install gyp: Undefined variable standalone_static_library in binding.gyp while trying to load binding ...