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

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

AngularJS and Select2's Multiple - Tags feature can display tags intermittently, showing some and hiding others as needed

Currently, I am implementing AngularJS along with select2 (not using ui-select). In my view, the following code is present: <select name="rubros" id="rubros" class="select2 form-control" ng-model="vm.comercio.tags" ng-options="rubro.nombre for rub ...

Converting JSON information into a JavaScript array of objects

I have a JSON file containing placeholder articles for testing purposes. I'm using jQuery to parse the data from the JSON file and create an array of objects with the retrieved information. Take a look at my JSON file: { "news": [ { ...

The React Native Android app encountered an error loading the JS bundle: updates made to index.android.js are not reflecting in the generated APK file

Setting up a react-native android project on my Windows machine has been successful so far. To run the project, I use the command react-native run-android and then the installed apk is generated on my phone. After making some changes in the index.android. ...

Tips for disabling viewport resizer while accessing the Console panel in Chrome using Control+Shift+J

Currently, I am utilizing the viewport resizer in Chrome to preview how my code appears on various devices. However, I have encountered an issue - whenever I try to access the console using ctrl + shift + j, the viewport resizer opens instead. You can obs ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

What approach do you recommend for creating unique CSS or SCSS styles for the same component?

Consider a scenario where you have a complicated component like a dropdown menu and you want to apply custom styles to it when using it in different contexts. This customization includes not only changing colors but also adjusting spacing and adding icons. ...

Modify the CSS when CKEditor is in focus

Implementing CKEditor in a symfony project using the FOS\CKEditor-bundle 1.2. I want to style the entire element containing CKEditor with a border when it is focused, similar to how questions are written or answered on Stackoverflow. By referencing a ...

A guide to spinning an image in every direction with CSS

I'm working on rotating an image in all directions using CSS and Vue.js. To demonstrate this, I have created a CodePen with the necessary code below. <div id="app"> <v-app id="inspire"> <div class="text-xs-center image-rotation" ...

Is your blockui overlay failing to cover the entire page?

I have implemented blockui to display a "Wait ... loading" popup on my webpage. It is mostly working fine, but I am facing a small issue where the overlay does not cover the entire width of the scroll window when I scroll right (although it covers the full ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

Having trouble with installing create-react-app for my_app using npm because it seems to be stuck on f

I've hit a roadblock while trying to create a react app on my 2011 MacBook Pro. To start, I downloaded the latest version of Node from their official website. Following the instructions from React documentation, I ran the following commands: npm uni ...

How can I leverage Express, AngularJS, and Socket.io to facilitate broadcasting and receiving notifications?

A new notification system is in the works. To illustrate, User 1 is initiating a friend request to User 2. The technologies being utilized include express.js, angularjs, and socket.io. When User1 clicks the button, a request is sent. On User2's end, a ...

When using Jquery, input can be appended on the last child element when a key

I am new to JavaScript and want to enhance my page's functionality using jQuery. Here is my current HTML: <div class="input_fields_wrap"> <div><ul class="inputList"></ul></div> </div> My goal ...

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

When incorporating pinia with Vue, encountering an error with the decorator that says "Error: Unable to access 'useCoreStore' before initialization" may happen

While implementing the vue-facing decorator in my current project, I encountered an issue with setting up pinia. The structure of my component resembles the example provided here: I have verified that decorators like @Setup are functioning correctly, ind ...

Drop the <span> element into a paragraph by utilizing JQuery's drag and drop feature

Trying to drag and drop <span> into <p>. The code is functional, but encountering 3 issues: When editing content inside <p> by typing (e.g. three words) and then dragging <span> into <p>, the newly typed words are consider ...

What is the best way to compare two strings without considering their capitalization?

Here is the issue I am facing: mytext = jQuery('#usp-title').val(); Next, I check if the text matches another element's content: if(jQuery("#datafetch h2 a").text() == mytext) { However, titles can vary in capitalization such as Space Mi ...