Learn the process of filtering an array using another array

I have a collection of items set up in the following format.

items = [
   { id: 1, 
     status : "Active"
     // Other fields
     tags : [{val: 'IGM', color: 'light-success' },
             {val: 'Gated Out', color: 'light-primary' },
            ]   
   },
   // ...
]

Now I want to filter these items based on their tags. The input for filtering is an array generated from a multi-select input.

For example:

[{value: 'Gated Out', label: 'GATED OUT'},  .. ]

I am able to filter data based on other fields which are strings, but struggling with filtering based on arrays like tags.

How can I adjust my current code to handle array-based filtering as well?

This is the approach I'm currently following;

  const handleTagsFilter = (value) => {
    let updatedItems = []

    const filterData = () => {
      if (
        status.length ||
        custom_tags.length
      ) {
        return filteredItems
      } else {
        return items
      }
    }

    setCustomTags(value)
    if (value.length) {
      updatedItems = filterData().filter((item) => {
        const startsWith = item.status.toLowerCase().startsWith(value.toLowerCase())

        const includes = item.status.toLowerCase().includes(value.toLowerCase())

        if (startsWith) {
          return startsWith
        } else if (!startsWith && includes) {
          return includes
        } else return null
      })
      setFilteredItems([...updatedItems])
      setCustomTags(value)
    }
  }

This function effectively filters strings based on conditions like matching the status field to "Active". However, I need assistance in adapting it to successfully filter arrays like tags.

Answer №1

Perhaps a solution could look similar to this:

const searchTerm = 'abc'.toLowerCase();
const filteredTags = results
  .map(value => value.tags.filter(innerValue => innerValue.val.toLowerCase().includes(searchTerm)))
  .filter(filteredValue => filteredValue.length)
  .reduce((accumulator, currentValue) => accumulator.concat(...currentValue), [])

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

After employing a combination of forEach and filter queries in JavaScript to sift through dropdown options, no results are being generated

Hey there fellow developers, I'm currently in the process of developing an app and have reached the stage where I am filtering elements using dropdowns. I am querying a JSON object and comparing it with the selected element in the dropdown at that mom ...

unanticipated redirection with Vue router

Here is the routing code snippet: // exporting for component use export var router = new VueRouter(); // defining routes router.map({ 'home': { component: Home, auth: true }, 'login': { component: L ...

Get names with specific characteristics by using a Javascript object that acts as an associative array

Can someone help me with my code? I'm trying to create an input box that, when I type in "A", will display the names of students who have earned "A" grades. I feel like I'm close to getting it right, but there's something missing. Any assist ...

Recognizing a component through various page loads

The title of this question may not be the best, but I hope my explanation clarifies what I'm trying to achieve. It's 4AM, so please forgive any confusion in my message. What I want to do is identify if a user-selected element appears on any page ...

"Is there a way to dynamically remap an array only when there are changes

One of the challenges I am facing is with a component called Page, which contains two components - Editor and Preview. Page has an array called items. [ { value: 0, text: 'Item 1' }, ... ] This array items is passed ...

Converting an object into an array using React and TypeScript

Extracted from a form is an object with input, output, and outputType fields that can vary between number, string, and boolean types. To display the information in a table without the output type, I have created a mapped obj. However, I also need to prese ...

Tips on converting comma-separated values into HTML table rows using <tr> tags

JSON Data { "catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"], "price": ["100", "8"], "qty": "", "qty2": ["", ""], "total_qty": "", "total": "", "mem": "10", "email_2": "", "ic_add": "890527-08-6136", "c ...

Extract specific index from a JSON array

I'm a beginner in Jquery and javascript, I am using ajax to upload an image and trying to fetch the image url. However, I keep encountering errors every time I try. Can someone assist me with this? Thank you! Here is the error message I received: Un ...

Error message: Unforeseen node express token problem

Whenever I attempt to call the endpoint provided below, Postman returns an error as shown: { "success": false, "error": "Unexpected token / in JSON at position 7" } Within the addFollowing function, you'll notice that I ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Only one admin account can be accessed at a time by multiple logins

I am looking to add a new feature to my app where only one admin can log in at a time. If someone else tries to log in with the same admin ID on another device, a warning should be shown, indicating that the user is already logged in and cannot access the ...

Learn how to collapse a list by clicking outside of it on the document with the following code: $(document).on("click"

I want to create a collapsible/expandable menu for my website. I had a version where hovering over a category would expand the subcategory, but what I really need is for the subcategories to expand when I click on a category and remain expanded until I cli ...

Having trouble running classes using Maven test with the Testng.xml file in the terminal, however, it runs smoothly in Eclipse

While I have been successful in running my solution through the testng suit in the Eclipse console, I am facing difficulties executing the testng.xml file via Maven integrated with Sauce Labs in the terminal. Output received on the terminal: ------------ ...

After modifying the template, the ReactDOM.render() function fails to work when called again

Initially, the render() function works perfectly. However, upon calling it again through one of the event handler functions, it fails to work. The Chrome DevTools console does not show any errors. The changes are made within the options array and then nee ...

The React hook useState is struggling to accurately map array objects

Recently, I encountered an issue with a form that sends an array of objects to another React Functional Component: import React, { useState } from 'react' import uuid from 'uuid/v1'; const NewMovieForm = ( {addMovie }) => ...

Troubleshooting issue with Gulp watch on Node v4.6.0

I'm currently facing a frustrating situation. I had a project up and running smoothly with a functioning gulpfile.js file, everything was perfect until I updated node to version 4.6.0. When I tried to report this issue on Gulp's git repository, t ...

Upgrading object based on dynamic data shifts in Vue using Vuex

My current task involves updating data in a component based on the selection made from a tabs list at the top of the page. The data is sourced from a Vuex data store, and after conducting tests on the data store, everything appears to be functioning correc ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...

What is the process for syncing ng-model with external data sources?

Here is a question that I have pondered: Let's consider the HTML code snippet below: <div id="container" ng-controller="Controller"> <my-tag ng-model="values"></my-tag> </div> Now, take a look at the controller defined a ...

Is the `visibility: hidden` property not functioning as expected?

I am trying to conceal the script for the photoset until it is fully loaded, but unfortunately the code below does not seem to be effective: JavaScript $('.photoset-grid').photosetGrid({ rel: $('.photoset-grid').attr("data-id"), gutte ...