What is the best way to retrieve an array of objects that have a property matching another array?

In my array, I have data structured like this:

array = [
  { name: "john", tag: ["tag1", "tag2"] },
  { name: "doe", tag: ["tag2"] },
  { name: "jane", tag: ["tag2", "tag3"] }
];

My goal is to create a new array of objects that only contain elements with both "tag2" and "tag3", excluding those with only "tag2" or both "tag1" and "tag2".

The desired result should be:

newArray = [{ name: "jane", tag: ["tag2", "tag3"] }];

To achieve this, I attempted the following method:

tags = ["tag2", "tag3"];
newArray = [];
tags.forEach(tag => {
  array.forEach(data => {
    data.tag.forEach(item => {
      if (item === tag) {
        newArray.push(data);
      }
    });
  });
});

However, instead of the expected outcome, I ended up getting all the items in the array.

Answer №1

If I have interpreted your request correctly, you are looking to scan through the main array and identify all elements whose tag property consists of an array that exactly matches ['tag2', 'tag3'].

To accomplish this, you can utilize the filter method based on the specified condition.

One potential solution is provided below:

 
const array = [
  {
    name: 'john',
    tag: ['tag1', 'tag2']
  },
  {
    name: 'doe',
    tag: ['tag2']
  },
  {
    name: 'jane',
    tag: ['tag2', 'tag3']
  }
];

const tagsToMatchOn = ['tag2', 'tag3'];

// Filter elements with tag property matching the specified tags
const newArray = array.filter(item => (
  item.tag.length === tagsToMatchOn.length && 
  tagsToMatchOn.every(t => item.tag.includes(t))
));

console.log(newArray);

If your intention is to locate items with a tag property containing both 'tag2' and 'tag3', along with additional tags, you may consider a strategy similar to this one:

const array = [
  {
    name: 'john',
    tag: ['tag1', 'tag2']
  },
  {
    name: 'doe',
    tag: ['tag2']
  },
  {
    name: 'jane',
    tag: ['tag2', 'tag3']
  }
];

const tagsToMatchOn = ['tag2', 'tag3'];

// Find elements with tag property including specified tags
const newArray = array.filter(item =>
  tagsToMatchOn.every(t => item.tag.includes(t))
);

console.log(newArray);

Answer №2

Although this solution may not be the most sophisticated, it successfully gives you the desired outcome.

array = [{name:'john',
          tag: ['tag1','tag2'] 
         },
         {name:'doe',
          tag: ['tag2'] 
         },
         {name:'jane',
          tag: ['tag2','tag3'] 
         }
        ];

const newArray = [];
for (let index = 0; index < array.length; index++) {
    if(array[index].tag[0] === 'tag2' && array[index].tag[1] === 'tag3') {
        newArray.push(array[index])
    }
}

If you prefer a more ES6 approach:

array.forEach(element => {
  if(element.tag[0] === 'tag2' && element.tag[1] === 'tag3') {
    newArray.push(element)
  }
});

Answer №3

Follow this approach to achieve it

Utilize the filter and every methods for this task.

Essentially, I am iterating through each element of the array (using filter) and then using every to check if the tag property of the element contains all the required tags. If it does, we include it in the final output; otherwise, we exclude it.

let arr = [{name:'john',
          tag: ['tag1','tag2'] 
         },
         {name:'doe',
          tag: ['tag2'] 
         },
         {name:'jane',
          tag: ['tag2','tag3'] 
         }
        ];
let tags = ['tag2','tag3'];
let op = arr.filter(e=> tags.every(el=> e.tag.includes(el)));
console.log(op);

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 placement of the Vuetify tooltip is incorrectly aligned when located in the footer section

Having trouble fixing the issue with the Vuetify tooltip. After scrolling on the page, the tooltip moves up despite using fixed="true". Here is the code snippet causing the problem: <v-footer app inset fixed> <v-row align="center ...

The dropdown menu component in ReactJS is malfunctioning

I'm currently working on a form that includes a select box which fetches data from the server and posts it back to the same server. I have implemented the select box component from ant design. Unfortunately, I've encountered an issue with the ha ...

I am experiencing issues with the middleware not functioning properly after implementing a custom application with Next.js

I'm currently diving into Next.js version 13 and attempting to customize the app based on the standard documentation. However, it seems that the middleware isn't being invoked as expected. I suspect there might be something wrong with my implemen ...

The search function in the Vuetify datatable is unable to find the specified value

I came across the miss function on the Vuetify datatable, and I believe my configuration is correct. Below is my Vuetify datatable: <v-text-field v-model="search" append-icon="mdi-magnify" label="Search" single-line hide-d ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

The script is not functioning properly due to an error stating "(Uncaught ReferenceError: $ajaxUtils is not defined)"

I'm having trouble figuring out what the issue is (Uncaught ReferenceError: $ajaxUtils is not defined) document.addEventListener("DOMContentLoaded", function (event) { showLoading("#main-content"); $ajaxUtils.sendGetReque ...

"Learn how to showcase a picture in full-screen mode when the webpage is opened

I recently came across a script on Stack Overflow that allows me to select an image at random from an array. The script can be found here: Script to display an image selected at random from an array on page load However, I want to take this concept furthe ...

Vuetify's dialog feature allows for multiple videos to be played at once using a v-for

I'm currently facing an issue with my v-for loop that goes through a media array in order to play a video. The problem is that when I open my v-dialog, both models are displayed on top of each other. Additionally, the video keeps playing even after th ...

Name or Title of a Polygon/Polyhedron Using Three.js

My page contains a sample code that successfully retrieves the name of an object when a user clicks on it. However, the code works well with cubes and spheres but fails with polygons. To see how the clicks respond, you can check the console logs. What shou ...

Utilize jQuery method in HTML to perform parsing operation

Is it possible to invoke my jQuery function from within my HTML code? Here is the code snippet: HTML section: <td style="text-align:left;" align="left" > <div id="bulletin-timestamp" > doTimeStamp(${bulletinTimeStamp[status.index ...

Is it possible to pass parameters using getters in Nuxt?

When attempting to pass the ID using $route.params.id in my getters method, it's not functioning as expected. Within my component, I have an object called blogs; I would like to store this.$route.params.id in blogId and then utilize it in my getters ...

Altering the playback of a flash object using HTML or JavaScript

Can the playback speed of a flash object be adjusted without recompiling the object, like through HTML attributes or JavaScript? Appreciate any help in advance ...

Update the Laravel public directory

I need to update the public folder to public_html, but encountering issues with commands and functions still referencing the old public directory. While using Laravel+Vue for a single page application, my usual practice of renaming the public folder to pu ...

In which location can one find the compiled TypeScript files within an Angular 2 project?

As a newcomer to learning Angular 2, I've come across tutorials that mention all compiled files should go into the dist folder. These compiled files refer to typescript files transpiled into JavaScript. However, upon creating my project using Angular ...

Guide on creating an autonomous select-all checkbox to show table columns

How can I create checkboxes with a "Select all" option and the following functionality: Check one or more checkboxes to show specific table columns. Uncheck them to hide the columns (toggle). Select the "Select all" checkbox to display all table columns. ...

Updating the value of a $scope variable located within an included template in AngularJS

My setup is quite simple as outlined below. The issue I'm facing is that out of the two variables I define within the $http success callback, only one is reflected in the UI. In this scenario, I am attempting to display progress when the controller l ...

What are the steps to generate a multiline chart using d3.js with json data specifically formatted for nvd3?

I attempted to create a multi-line chart using nvd3, but encountered roadblocks when trying to make significant modifications. I am considering building my own chart using d3js directly, but I'm finding it challenging to grasp the concept of 'thi ...

Update the text within a table in real time by simply checking a box

I've got some data in JSON format that I've converted into an HTML table. Now, my goal is to update the text from False to True if a checkbox is checked. How can I achieve this? Below is the code used to create the HTML table: $.each(result, fu ...

The click event fails to trigger on dynamically loaded Ajax content

I've encountered an issue while loading content using ajax from external HTML Files. After the content is loaded, the click event doesn't seem to be working in Safari (including mobile safari) for any of the newly loaded elements such as ul, li, ...

Issues with ng-show functionality occurring during the initialization of the webpage

While working on a webpage using HTML, CSS, and Angular.js, I encountered an issue where the page content would not display properly upon loading. The objective was to show selected content based on user choices from a dropdown menu. Although the filtering ...