Extract all objects from an array where a specific field contains an array

 data:[
        {
           id:1,
           tags:['TagA','TagB','TagC']
         },
         {
           id:2,
           tags:['TagB','TagD']
         },
         {
            id:3,
            tags:['tagE','tagC']
         }
      ]

filterCondition:{tags:['TagA','TagB']}

Expected Output: [
                   {
                     id:1,
                     tags:['TagA','TagB','TagC']
                   },
                   {
                     id:2,
                     tags:['TagB','TagD']
                   }
                 ]

Is there a potential method in typescript to achieve the desired result using the filter function? When the 'tags' field is not an array, it works fine. However, when it's within an array, the code does not produce the expected output.

I have attempted a solution but encountered failures:

   data.filter(o => Object.keys(filterCondition).every(k => filterCondition[k].some(f => o[k] === f)));

Answer №1

Utilize the filter method along with includes

const items = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];
      
const filterItems = tag => items.filter(item => tag.some(t => item.tags.includes(t)));

console.log(filterItems(['TagA', 'TagB']));

Minor adjustment in the conditional array form:

    let filterArray={tags:['TagA','TagB']}

    const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];

    output= data.filter(o => Object.keys(filterArray).every(d => filterArray[d].some(t => o[d].includes(t))));

Answer №2

const allData = {
  items: [{
      id: 1,
      categories: ['CategoryA', 'CategoryB', 'CategoryC']
    },
    {
      id: 2,
      categories: ['CategoryB', 'CategoryD']
    },
    {
      id: 3,
      categories: ['CategoryE', 'CategoryC']
    }
  ],
  filterQuery: {
    categories: ['CategoryA', 'CategoryB']
  }
};

console.log(allData.items.filter(item => allData.filterQuery.categories
  .some(query => item.categories.join(',').includes(query))));

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

The Bootstrap modal fails to open

I am currently working on implementing a Navbar button that triggers a Bootstrap modal containing a form. While looking for resources, I stumbled upon a useful script at https://gist.github.com/havvg/3226804. I'm in the process of customizing it to su ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

AngularJS: incorporating various functionalities within a single controller

I have a basic AngularJS controller that I am working on, and I would like it to include two separate functions: var app = angular.module('searchApp', []); app.controller('searchCtrl', function($scope, $http, $log) { //Function 1 ...

Can you explain the distinction between export/import and provide/inject in Vue3?

Can you explain the difference between export/import and provide/inject in Vue3? // parent const data = provide('data', ref(0)) // child const data = inject('data') // parent export const data = ref(0) // child import { data } from & ...

Creating a personalized Autocomplete feature using React Material-UI with the help of the renderInput method

I'm currently using a React Material UI Autocomplete component, similar to the one in the official documentation. For example, let's consider a list of countries: import * as React from 'react'; import Box from '@mui/material/Box& ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

JQuery HTML form validation continues to send emails even when there are blank entries

I've set up an HTML form with three required fields, and I'm trying to prevent the form from submitting an AJAX call if those fields are left empty. $("#contact").submit(function(e){ e.preventDefault(); var ajaxurl = '<?php echo ...

Sorting an object array by date is causing a problem

UPDATE: Finally cracked the code on this issue. I initially assumed that Date was interpreting the date ("29-04-2020") as DD-MM-YYYY, when it should actually be MM-DD-YYYY. For instance, here's an object array I'm working with: let t ...

Tips for creating a universal function to connect html elements in AngularJS

As a beginner in angularJS, I come with prior experience writing common functions for binding html controls in JS. However, I am looking to apply the same approach in angularJS. I understand the angular way of binding html controls, but my goal is to str ...

Guide on making a button display an image, then switch back to the initial image when clicked again

Currently, I have this neat feature on my website where there's a button that toggles the image/background color - kind of like a dark mode switch. The background change is working fine, but I'm encountering some challenges with organizing the im ...

Having trouble sending values via POST request in Node.js using Express

Currently, I am in the process of learning how to use Express (v4) with Node.js. My main goal right now is to create a basic REST API. This API specifically focuses on one endpoint: /orders. The main functionality I am trying to achieve is the ability to r ...

Leverage the compiler API to perform type inference

Exploring TypeScript's compiler API for basic type inference has proven to be a challenge with limited helpful information found in documentation or online searches. My goal is to create a function inferType that can determine and return the inferred ...

Is there a way for me to retrieve the value nested within an object within another object from this Api response?

Hey there, I'm currently struggling to retrieve the value of faceit_elo from within the csgo object. I attempted using data.games.csgo.faceit_elo but unfortunately it didn't yield any results. Any suggestions on how to access this value would be ...

The never-ending cycle of an Angular dropdown linked to a function being repeatedly invoked

I am currently working with a PrimeNg dropdown that is fetching its options through a function call. However, I have noticed that this function is being called an excessive number of times. Could this potentially impact the performance or any other aspect? ...

The contenteditable DIV function is experiencing issues with Angular's two-way binding feature in the Firefox browser

After making my div contenteditable and triggering ngx-popover on keyup to display search results based on searchText, I am in need of two-way binding along with content editability. However, I prefer using a div instead of an input element: <span> ...

What is the best way to dynamically add fields to every object in an array of Firestore documents using RxJS?

Trying to solve a challenging RxJS issue here. In my Angular service class, I initially had a method that fetched data from the Firebase Firestore database like this: async getAllEmployees() { return <Observable<User[]>> this.firestore.co ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

I am having difficulty with understanding sub-arrays

I have an array with various first indexes and I need to extract all instances of the client_created string without specifically referencing each index like $array[688]["client_created"], $array[690]["client_created"]... Is there a way to extract all occu ...

Top technique for creating a unique cursor image for a website

I'm looking for the most efficient way to create a custom cursor image for my CSS/HTML5 website without using Flash. Ideally, I would like to implement this using CSS rather than resorting to Javascript. If Javascript is necessary, I want to know whic ...

Showing text above bars in MUI X BarChart

I am currently utilizing the <BarChart> component from @mui/x-charts (version "^6.19.1") and I am looking to enhance readability by displaying the data values on top of each bar. Current Output: view image description here Desired Outc ...