Utilizing array.filter() to retrieve objects with values containing specified keywords

In my node.js project, I have an array named products that is structured as follows:

[ {  product_id: 'adidas-training-shoes',
      title: 'Adidas Training Shoes',
      description: 'description',
      brand: 'brand',
      variants: [ [Object], [Object] ],
      thumbnail_url: 'url' },
   {  product_id: 'nike-running-shoes',
      title: 'Nike Running Shoes',
      description: 'description',
      brand: 'brand',
      variants: [ [Object], [Object], [Object], [Object] ],
      thumbnail_url: 'url' },
   {  product_id: 'vans-sneakers',
      title: 'Vans Sneakers',
      description: 'description',
      brand: 'brand',
      variants: [ [Object], [Object], [Object] ],
      thumbnail_url: 'url' } ]

Additionally, I have a configuration file named config.json that includes a list of keywords along with other settings:

{
   "keywords": [
    "vans",
    "nike" ]
 }

I aim to filter the products array using products.filter() to retrieve the items whose product.title contains any of the keywords listed in config.keywords.

I am relatively new to JavaScript, especially ES6, and I'm open to switching to a different version if it simplifies the process. Despite conducting research prior to posting this question, I hope it offers a unique perspective on the issue at hand.

Answer №1

const selectedItems = products.filter((item) => (
  configuration.searchTerms.some((term) => (
    item.name.toLowerCase().includes(term.toLowerCase())
  ))
));

If any of the search terms specified in the configuration are found in the item name, return true.

Feel free to remove the .toLowerCase() if case-sensitivity is not a concern.

Answer №2

You can utilize a mix of filter and some method

let filtered = products
    .filter(product => 
        product.title.split(' ')
            .some(s => config.keywords.includes(s.toLowerCase())))

const config = {
  "keywords": [
    "adidas",
    "nike"
  ]
}
let products = [{
    product_id: 'adidas-training-shoes',
    title: 'Adidas Training Shoes',
    description: 'description',
    brand: 'brand',
    variants: [
      [Object],
      [Object]
    ],
    thumbnail_url: 'url'
  },
  {
    product_id: 'nike-running-shoes',
    title: 'Nike Running Shoes',
    description: 'description',
    brand: 'brand',
    variants: [
      [Object],
      [Object],
      [Object],
      [Object]
    ],
    thumbnail_url: 'url'
  },
  {
    product_id: 'vans-sneakers',
    title: 'Vans Sneakers',
    description: 'description',
    brand: 'brand',
    variants: [
      [Object],
      [Object],
      [Object]
    ],
    thumbnail_url: 'url'
  }
]

let filtered = products.filter(product => product.title.split(' ').some(s => config.keywords.includes(s.toLowerCase())))

console.log(filtered)

Answer №3

const searchWords = ["adidas", "reebok"];

const allProducts = products.filter(product => {
    return searchWords.some(word => {
        return product.name.toLowerCase().includes(word);
    });
});

Answer №4

Just an example

const filteredProducts = products.filter(function(prod){
   let include = false;
   config.keywords.forEach(function(word){
      let result = prod.title.toLowerCase().indexOf(word);
      if (result != -1){
         include = true;
      }
   });
   return include;
});

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

What is the best way to pass cookies between domain and subdomain using nookies?

Recently, I've been facing some challenges with sharing cookies between my app and website while using nookies. Below is the code snippet from my app.mydomain.com file: //setCookies to main domain setCookie(null, 'jwt', login ...

Ongoing state configuration in a React hook

My custom hook: export function useToken2() { const { data: session, status } = useSession(); const [token, setToken] = useState<string | null>(null); useEffect(() => { if (status === 'authenticated' && session?.accessToken) { ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

Choosing the number of items for each cartItem in KnockoutJS: A comprehensive guide

Greetings! I am new to using knockout and I am attempting to automatically select the quantity for each item in my cart from a dropdown menu. Below is the code I have written: VIEW <div data-bind="foreach: cartItems"> <h3 data-bind="text: ful ...

Utilizing JQuery for a smooth animation effect with the slide down feature

I have a question about my top navigation bar animation. While scrolling down, it seems to be working fine but the animation comes with a fade effect. I would like to achieve a slide-down effect for the background instead. Since scrolling doesn't trig ...

A quicker method for deleting an element from an array based on its index

Last year, I posted this and now I feel there could be a simpler solution. I am looking to remove an item from an array based on its index. Even if the array contains duplicate values, I want to be able to remove the item by its index. Here is a common ex ...

Encountering an issue with Node JS request and cheerio while parsing an HTML page

Greetings all, I am currently attempting to parse a website using Node.js (utilizing request and cheerio). The issue I am encountering is that I am trying to extract the href from the site, but I can only find it within the site's window. Unfortunatel ...

Calculator app with Next.js: Using keyboard input resets the current number state in real-time

While developing a basic calculator application with Next.js, I encountered an issue. The functionality works correctly when the user interacts with the HTML buttons, but when trying to input numbers using the keyboard, the state resets to 0 before display ...

Automatically Modify Uploaded Files on the Server

There is one thing that has caught my attention. I am interested in working with scripts that can automatically edit a file once it's been uploaded. For example, imagine having a form where someone uploads an HTML file. The script would then edit spe ...

best way to sort through an array using jquery in javascript

Is there a way to filter a jQuery array like in SQL server with "Like % %"? var array=[ {"job_category":"hello sir","job_location":"hello dear"}, {"job_category":"dear kumar ","job_location":"sir"}, {"job_category":"testts ssss ss","job_location":"hello t ...

Using Javascript, incorporate a string variable into the response

Currently, I'm working with a node.js program and I've come across this response: 'Content-Disposition': 'attachment; filename="tts.mp3"' Instead of using "tts.mp3," I have a variable named textToConvert. How can I modify it ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

Troubleshooting three.js problem: Unexpected application malfunction in Chrome due to outdated code incompatible with the latest three.js library

Several weeks ago, my three.js (R48) applications were running smoothly until I encountered issues with Chrome where they no longer work. Here are the initial error messages I received: WebGL: INVALID_OPERATION: getAttribLocation: program not linked skyW ...

Is there a way to display an XML listing recursively similar to the functionality of an ASP:MENU in the past?

I have been working on converting a previous asp:menu item to JavaScript. Here is the JavaScript code I have come up with: function GetMainMenu() { var html = ''; var finalHTML = ''; finalHTML += '<d ...

Using v-bind to dynamically set styles in Vue.js

While utilizing v-bind:style to apply dynamic values, I encountered an issue where v-bind:style did not seem to work. However, in the console, I verified that v-bind:style was receiving the correct value (:style='{ color : red (or any other value) }&a ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

generate a fresh array with matching keys

Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...

What is the method for displaying x-axis dates below a highchart?

I'm encountering an issue with Highcharts where dates are not showing under the chart when passing series data as an array of objects. See result image The documentation mentions using an object instead of an array ([1649153340000, 45]docs I need t ...

What is the best way to implement my custom toolbar button to utilize the form's validation function within react-admin?

I have developed a unique Toolbar with a custom button that is supposed to mimic the behavior of the standard SaveButton but also perform additional actions after the form is submitted. The form should only be able to submit if it passes validation, and an ...