Access the value within an object that contains an array and compare it with a different array

array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a3d2e6f7e1e6bcf1fdff">[email protected]</a>', group_ids: ["25"], username: 'test1'},
          {id: 2, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4b0a1b7b0f684b0a1b7b0eaa7aba9">[email protected]</a>', group_ids: ["22"], username: 'test2'},
          {id: 3, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f7b6a7c7b3c4f7b6a7c7b216c6062">[email protected]</a>', group_ids: ["25", "20"], username: 'test3'},
          {id: 4, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32465741460672465741461c515d5f">[email protected]</a>', group_ids: ["23"], username: 'test4'}]

array2 = [25, 22];

I am trying to extract the email addresses from array1 that have group_ids matching those in array2. However, my current method is not giving me the correct result. Any assistance would be greatly appreciated.

var user_groupId = [];
var emails = [];
var obj = [];
for (var i=0; i < array2.length; i++) {
    obj.push(array1.find(o => o.group_ids.find( b => b == array2[i])));        
}

for (var i=0; i< obj.length; i++){
    emails.push(obj[i].email);
}
console.log(emails);

As of now, the output Array is ["[email protected]", "[email protected]"], however, it is missing "[email protected]". Thank you for your help.

Answer №1

Utilize the functions filter, map, and some for your solution. Additionally, it is advised to maintain consistency in the data types of your ids:

array1.filter(item => item.group_ids.some(id => array2.includes(+id))).map(item => item.email)

The use of +id ensures conversion of the string array1 items to integers

Answer №2

I believe this issue is being over-complicated, especially when comparing different data types such as strings and numbers. There are multiple approaches to tackle this problem, but it is crucial to have a clear understanding of the goal of our code. Check out the following comments and links for a detailed explanation of my suggestion...

var array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02766771763342766771762c616d6f">[email protected]</a>', group_ids: ["25"], username: 'test1'},
          {id: 2, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="780c1d0b0c4a380c1d0b0c561b1715">[email protected]</a>', group_ids: ["22"], username: 'test2'},
          {id: 3, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295d4c5a5d1a695d4c5a5d074a4644">[email protected]</a>', group_ids: ["25", "20"], username: 'test3'},
          {id: 4, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74001107004034001107005a171b19">[email protected]</a>', group_ids: ["23"], username: 'test4'}]
var array2 = [25, 22];

function group_Emails(list_array, id_array) {

    var result = [],
        email;

    /* loop over list_array */
    list_array.forEach(obj => {
        
        /* for each item in list_array (obj)
           convert group_ids to integers and
           store in new list_group_ids array */
        var list_group_ids = obj.group_ids.map(num_str => {
            return parseInt( num_str, 10 )
        });
        
        /* compare id_array to list_group_ids */
        id_array.forEach(num => {
            
            /* does list_group_ids contain num? */
            list_group_ids.includes( num ) && (
                /* if so grab email from obj */
                email = obj.email,
            
                /* add email to result if not present 
                   (avoids duplicate entries) */
                -1 === result.indexOf( email ) && result.push( obj.email )
            );
        })
    });

    return result;
}

console.log( group_Emails(array1, array2) );
// => [ "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82f6e7f1f6b3c2f6e7f1f6ace1edef">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec98899f98deac98899f98c28f8381">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8bffeef8ffb8cbffeef8ffa5e8e4e6">[email protected]</a>" ]

I trust this provided clarification. :)


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

JSON output for creating interactive charts using Highcharts

After much perseverance, I have successfully generated a chart. However, I am facing an issue where the data from JSON is not being displayed - resulting in a blank chart. The chart options currently look like this: series : [{ name: '2000' ...

Reviewing file information prior to submission

Is there a way or method we can utilize to validate file details (extension and size) before the form is submitted by the user? I have limited knowledge of jQuery or JavaScript, so please provide detailed assistance if that is the solution. I envision tha ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

Get your hands on large files with ease by utilizing jQuery or exploring alternative methods

Within my User Interface, there exists an Advanced Search section where the user can select from 7 different options as depicted in the diagram. Based on these selections, a web service is triggered. This web service returns search results in JSON format, ...

Exploring the array push method in ES6 destructuring

Is it possible to use something similar to the destructing assignment feature in ES6 to write cleaner code when pushing items into an array? I'm unsure how to implement it properly, especially within a context like Vue.js. Here is an example code snip ...

Verify the positions of surrounding cells in the simulation of Game of Life using C programming

My current project involves recreating Conway's Game Of Life in C. One aspect of the code I'm focusing on is checking the status of neighbors surrounding a given coordinate in a 2D array, determining if they are DEAD or ALIVE: int checkNeighbor( ...

Change the hover effects on the desktop to be more mobile-friendly

In my desktop version, I have implemented some code that enables hovering over a button to display additional information or text. How can I modify this for mobile so that nothing happens when the button is tapped on? .credit:hover .credit-text, .credit- ...

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...

Avoid activating ng-blur when ng-keydown is triggered in AngularJS

Currently, I am working on a project involving angularJS and I am facing an issue with the execution of ng-blur conflicting with ng-keydown. The problem arises because ng-keydown causes the element to lose focus at a certain point. The HTML code in questi ...

What is the proper way to assign labels to an array?

I have a table in my Database where my script is storing its values. I am trying to achieve the following task: if a "description" already exists, I want it to display once but count up all the duplicate rows. The code below accomplishes what I need, howev ...

Enhancing User Experience with Cascading Dropdown Menus in MVC 5

I've been working on this project for a few days now, trying to get Cascading Dropdownlists to function properly. I'm having an issue where my State dropdownlist is not populating and no error message is displayed when the Ajax call fails. What c ...

Unlocking the Secret Code

Presenting the question: checkPassword([["Peter", "P"], ["Sarah", "S"], ["Ethan", "R"]], {"Peter": "P", "Sarah": "Q", //"Ethan":"E"}) ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

What seems to be the issue with this Discord.js kick command code? It's not

Okay, so I'm in the process of creating a kick command for my Discord bot. The issue I'm encountering is that when no reason is specified or if a user is not mentioned to be kicked, the bot responds correctly but does not actually kick the user. ...

Tips for finding the specific value's array index in PHP

I have retrieved the following array from a database: Array ( [0] => stdClass Object ( [cSize] => 120x60 [cFilename] => 29955_120x60.png [dtLastUpdated] => 2017-06-11T18:18:34-07:00 [cURL] => http:// ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

Troubleshooting the issue: "Error - 'Missing "data" payload in the request' when using Vue.js with Strapi"

When attempting to create a new entry in strapi by sending a post request in vue.js, I encountered the following error: message: Missing "data" payload in the request P.S: I also need to be able to upload files. I have read that using formData is ...

Remove the bottom border from the active tab by utilizing the <div> and <a> elements

I am facing an issue with a tabbed menu on my webpage. While the menu is functioning correctly, I am struggling to remove the bottom border from the active tab. You can view all of my test code here. While I have come across solutions using <ul> an ...

Script for converting Fixed Positioned Elements to Static

I am frequently finding that elements on web pages are causing disruptions due to their fixed positioning. I am exploring ways to disable the position: fixed CSS rules on any website I visit. To address this issue, I have developed a userscript specifical ...

Using AJAX to upload an image and passing multiple parameters

I'm facing an issue when trying to upload an image along with other input text in a form and send it to ajax_php_file.php. Whenever I upload the image, all my input text fields appear empty. Any assistance would be greatly appreciated. Thank you very ...