A guide on determining if any item from an array is present in an object's array property and iterating through all objects in JavaScript

After searching for a solution to my specific case, I couldn't find one among similar questions. So, I apologize if this seems like a duplicate.

I'm currently working on creating a filter for my website and have encountered an issue regarding marker objects and their corresponding array of tags (referred to as 'types').

Essentially, when a user selects certain types of markers to display, these choices are stored in a 'selectedFilters' array as strings. My goal is to only show the markers whose types match those selected by the user. In other words, any marker object that contains at least one selected type in its 'types' array should be displayed.

const markers = [
{
type: ['Paper', 'Plastic']
},
{
type: ['Burnable', 'Plastic']
}
{
type: ['NotBurnable']
}
.
.
.
]

const selectedFilters = ['Burnable', 'Plastic']

const filteredMarkers = ????

My approach involves using the filter method along with some techniques to compare each object's types array with the selected filters and return only the matching objects. While I've managed to achieve this with a hardcoded string, I am struggling to implement it with an actual array:

const filteredMarkers = this.markers.filter(
          marker => marker.type.some( type => type == 'Plastic') 
        )

I would greatly appreciate any advice, tips, or suggestions on how to dynamically replace the hardcoded string with the actual array and iterate through it effectively. Is there a different approach to building filters in a vue project?

Answer №1

Great effort! You're almost there. Make sure to verify if the selectedFilters .includes() any of the marker types.

const markers = [
  {
    type: ['Paper', 'Plastic']
  },
  {
    type: ['Burnable', 'Plastic']
  },
  {
    type: ['NotBurnable']
  }
]

const selectedFilters = ['Burnable', 'Plastic']

const filteredMarkers = markers.filter(
  marker => marker.type.some(type => selectedFilters.includes(type))
)

console.log(filteredMarkers)

Answer №2

let items = [
    {
        categories: ['Fruit', 'Vegetable']
    },
    {
        categories: ['Meat', 'Vegetable']
    },
    {
        categories: ['Meat']
    }
]

let selectedCategories = ['Meat', 'Vegetable']

let filteredItems = items.filter(function(item, index, array) {
    return item.categories.some(category => selectedCategories.includes(category));
});

console.log(filteredItems);

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 reason why JavaScript doesn't treat "1-1" as 0 in an operation like it does with "123" to 123 during calculations

When dealing with JavaScript, the difference between "123" and "1-2" can be confusing. While "123" is recognized as a string type with a numerical value, "1-2" is also a string type but it does not allow for multiplication. Why doesn't JavaScript hand ...

Enhancing the Rendering of React's props.children

I have set up my code like this: // Parent.js class Parent extends React.Component { render() { return { this.props.children } } } // Child.js class Child extends React.Component { render() { let message; const greet = ...

No duplication of Collada material present

I imported a collada model (.dae) into Three.js and encountered an issue with the object's material. Ideally, the material should appear as follows: However, it currently looks like this: The color is not an issue; I can modify the lighting within t ...

Enhance User Experience with the Tooltip Feature and Customized

Here is the jQuery code I am using to style my tooltips: $(function() { // select all input fields within #tooltips and attach tooltips to them $("#tooltips :input").tooltip({ // place tooltip on the right edge position: "cen ...

Displaying the contents of a slot in various locations within a web component

The Challenge I am currently utilizing Angular and its Angular Elements to produce Webcomponents. My goal is to allow clients the flexibility to pass custom icons into slots, enabling them to control the appearance of the icons being used. However, this ...

In what way can data be retrieved from within a useEffect block externally?

Essentially, I'm facing an issue with retrieving data from the DateView component in my ChooseCalendar component. The code that retrieves this data is located within a useEffect block due to passing a dateType variable as part of a useState to the com ...

Finding the initial occurrence of a capital letter within a string with PHP

I have an array where each word contains a different letter in uppercase like: aPple, Orange, baNana, mANgo, Papaya My goal is to determine the position of the first capital letter in each word and order them accordingly. The word with the first capita ...

Transform a string representing a specific time frame into a Unix timestamp using jQuery or JavaScript

I am trying to generate a Unix Timestamp for each date/time string that is generated within a foreach loop. Can anyone provide guidance on how to convert the string Mon Aug 08 2016 10:09:42 GMT+0100 (BST) into a Unix Timestamp to facilitate comparison? O ...

Is it really impossible to post complex JSON parameters with Restangular?

Is it possible to send a complex JSON object to a PUT route using Restangular? Restangular.one('model3ds', model.uuid).put( api_key: "blabla" model3d: { is_public: true } ) However, the data sent by Restangular appears as: ...

Turn off a feature on older buttons

For my project, I am looking to dynamically add specific elements like buttons. However, every time a new button is added, the function call for the old button gets duplicated. var btnElem ='<button type="button"class="doSomething">Button< ...

What is the correct way to assign a $scope variable after a successful ajax call?

Currently, I am working with Symfony and AngularJs 1.6.8 along with Symfony 3.4. Below is the configuration setup that I have: base.html.twig <html lang="en" data-ng-app="CeocApp" ng-controller="CeocController"> //css for the app <link id="ng ...

Unable to reference a file in a local directory using href in HTML

I'm attempting to create a hyperlink to a local pdf file. I have discovered that using an absolute path will open the pdf in a new tab on my site. However, when I try to use a relative path, the console shows a warning "No match found for location wit ...

Reading text data and characters into a 2D array using C++

I am struggling to read text into an array called arrayA[][] which contains both data and characters. Unfortunately, my code is unable to calculate the data correctly as all elements turn out to be 0.000 when I try to output arrayA[][]. Can someone pleas ...

What is the best way to rearrange elements within an object when there is no predetermined starting order?

Someone assisted me in refining this code snippet import React, { useEffect, useState } from "react"; import _ from "lodash"; // const SeleccionClientes = ""; const items = [ { client: "Microsoft", idClient: 0, idProjectType: 1, project ...

Refine your search with a JSON object description in expressJS and UnderscoreJS

[ { "id": 1, "description": "Empty the garbage bin", "completed": false }, { "id": 2, "description": "Dine out for dinner", "completed": false }, { "id": 3, "description": "Exercise at the fitness center", "com ...

JavaScript - the global and local variable dilemma

REVISED2: I'm encountering an issue with converting images to canvas using Pixastic in HTML5. How can I 'return' this converted image back to a global variable? Any suggestions? <img id="mainIllustration" alt="main illustration" src="Img ...

Creating JOIN tables within the create action involves assigning related ids to each table

I am currently working on a room reservation system that involves including options for each room. Data related to the options and their join table, reservation_options, are successfully inserted into the params. However, I am facing an issue with assignin ...

Encountering a rendering error with Jest while trying to load a functional child component

I encountered an error message stating Error: Uncaught [Error: Child(...): Nothing was returned from render while testing the Parent component. Below are the relevant files that were involved: /components/Page/Children/Child.js import React from "re ...

Steps to retrieve component values within the same component

I am currently working on developing a React component where I need to manage the checked status of checkboxes and select options when a change event occurs. However, I am unsure of how to retrieve the value of the checked checkboxes and update the state a ...

Transfer the array using Ajax to a PHP script

I have an array generated using the .push function that contains a large amount of data. What is the most effective way to send this data to a PHP script? dataString = ??? ; // Is it an array? $.ajax({ type: "POST", url: "script.php" ...