Comparing two arrays of objects in Javascript to identify common values and implement modifications

var nickNames = [
  {
    nickName:"Father",
    emailAddress:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec888d88ac888d88c28f8381">[email protected]</a>",
  },
  {
    nickName:"Mother",
    emailAddress:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff929092bf929092d19c9092">[email protected]</a>",
  },
  {
    nickName:"Bestie",
    emailAddress:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77151111371511115914181a">[email protected]</a>",
  }
]

var emails = [
  {
    from:"Dad Dadson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30545154705451541e535f5d">[email protected]</a>>"
  },
  {
    from:"Mom Dadson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7815171538151715561b1715">[email protected]</a>>"
  },
  {
    from:"Brother Dadson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98faeaf7d8faeaf7b6fbf7f5">[email protected]</a>>"
  }
]

for (var i=0; i < emails.length; i++) {
  emails[i].from.replace(/ *\<[^)]*\> */g, "")
}

for (var i=0; i < emails.length; i++) {
  if (emails.find(email => email.from) === nickNames.find(nick => nick.emailAddress)) {
    emails[i].nickName = nick.nickName
  }
}

Attempting to achieve two goals:

  1. Check both arrays for any matches between:
nickNames.emailAddress

and

emails.from

The regular expression used to extract the email address works in a different part of my code, but not here.

  1. If there is a match, add a new key-value pair in the matching email array element, with the corresponding nickname.

Expected outcome:

emails = [
  {
    from:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294d484d694d484d074a4644">[email protected]</a>",
    nickName: "Father"
  },
  {
    from:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573a383a173a383a7934383a">[email protected]</a>",
    nickName: "Mother"
  },
  {
    from:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0818052a08180544090507">[email protected]</a>"
  }
]

Appreciate any help you can offer!

Answer №1

Your regular expression seems to be deleting the email address from the from property instead of preserving it. I have included a different regex below that extracts the email address during comparison and disregards everything else.

const nickNames = [
  {
    nickName:"Dad",
    emailAddress:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a7e7b7e5a7e7b7e34797577">[email protected]</a>",
  },
  {
    nickName:"Mom",
    emailAddress:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c4c6c4e9c4c6c487cac6c4">[email protected]</a>",
  },
  {
    nickName:"BFF",
    emailAddress:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="791b1f1f391b1f1f571a1614">[email protected]</a>",
  }
]

let emails = [
  {
    from:"Dad Dadson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45212421052124216b262a28">[email protected]</a>>"
  },
  {
    from:"Mom Dadson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb969496bb969496d5989496">[email protected]</a>>"
  },
  {
    from:"Brother Dadson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="07657568476575682964686a">[email protected]</a>>"
  }
]

emails.forEach(email => {
  const match = nickNames.find(nickName => nickName.emailAddress === email.from.replace(/^(.* )<(.+)>/, "$2"));
   if (match) {
       email.nickName = match.nickName;
   }
});
console.log(emails);

Answer №2

To achieve the expected result, regular expressions are not necessary-

var users = [
  {
name:"John Doe",
email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="123456789abcde">[email protected]</a>",
  },
  {
name:"Jane Smith",
email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="56789abcde12">[email protected]</a>",
  },
]

var contacts = [
  {
from:"Doe <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="485abcde26">[email protected]</a>>"
  },
  {
from:"Smith <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89abcde56">[email protected]</a>>"
  }
]

users.forEach(item=>{
    contacts.forEach((entry)=>{
        if(entry.from.includes(item.email))
        {
            entry.name = item.name;
        }
    });
});

console.log(contacts);

Answer №3

function createEmailToNickNameMapping(emails, nickNames) {

  // This function creates a mapping from email addresses to nicknames
  const addKeyValue = (map, { nickName, emailAddress }) => {
    map.set(emailAddress, nickName);
    return map;
  };

  // Utilizing Array#reduce for creating the mapping 
  const emailToNickNameMap = nickNames.reduce(addKeyValue, new Map());

  // Regular expression for extracting emails in <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8d9d80af8d9d80c18c8082">[email protected]</a>> format
  const regexpEmail = new RegExp(/\<(.*)\>$/);
  
  // Using Array#map function to process each email entry
  return emails.map(({ from }) => {
    // Extracting email from the pattern <email>
    const email = from.match(regexpEmail)[1];

    // Checking if there is a nickname associated with the email
    const nickName = emailToNickNameMap.get(email);
    if (nickName) {
      return { email, nickName };
    } else {
      return { email };
    }
  });
}

const result = createEmailToNickNameMapping(emails, nickNames);
console.log(result);

This is a more functional approach that can yield better performance with larger datasets.

Consider exploring sets, maps, and objects as alternative data structures for efficient item searches in similar scenarios.

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

What steps should I take to resolve the issue concerning my highValue return error?

Trying to figure out how to make doubles work with integers and running into an error with the return highValue code stating "Possible loss of precision, required: int, found: double". This is for a class project, and below is the snippet of code: packa ...

What is the best way to manage global data in AngularJS?

Is it considered a best practice to store user data, such as profile name, in the $rootScope in AngularJS when it needs to be accessed in multiple routes? If not, what is the recommended approach for storing this type of information? ...

Prevent the ability to drag and drop within specific div elements

Having trouble disabling the sortable function when the ui ID is set to "comp". Can't figure out what's going wrong, hoping for some assistance here. $(".sort").sortable({ // start sortable connectWith: ".sort", receive: function ...

Storing a collection of images simultaneously in Firebase Storage and saving their URLs in a Firestore document using Firebase v9

I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is create ...

Bind AngularJS data to select elements

I am encountering an issue with data binding on a select tag, despite following the guidelines in the documentation. Here is my select element: <select id="start-type" ng-model="startType"> <option value="day-of-week">Day of the week</op ...

Iterate through the input values using a for loop and output the value of each individual input

I am working on an express app where I need to loop through data in my EJS file to create 5 hidden input fields, each with a unique value. However, I am struggling to extract the values of these inputs using JavaScript. Despite trying multiple methods, I ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

Refresh Image with Node.js

Seeking guidance in the right direction! I have a NodeJS application that is currently displaying an image sourced from a local directory. This image, stored locally, undergoes updates periodically through an OpenCV script. However, I am facing an issue w ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

The challenges of implementing view changes with $state.go

In the code below, I am setting up a login process. The PHP file for this process is working correctly, but after successful login, the view does not change as expected: (function (){ var app = angular.module('starter', ['ionic']); va ...

As for the Pixel Art Creator feature, you can now switch between different modes and

I'm seeking assistance regarding my Pixel Art Maker project. I recently implemented two new features, toggle() and remove(). The issue I'm facing is that when I input numbers to create the grid and click the submit button, the grid is successfull ...

The ability to update a variable passed through the state in Link is restricted

Currently, I am in the process of updating the theme in my App using useState. The updated theme is passed to the Topbar Component as a prop, triggering console.log() every time it changes. The theme is then passed from the Topbar to the AboutMe Component ...

What would be the JavaScript counterpart to python's .text function?

When using Element.text, you can retrieve the text content of an element. Recently, in a separate discussion on SO, there was a Python script discussed that scraped data from the followers modal of an Instagram account. The script is designed to capture t ...

Transforming the output of a MySQL query into a JSON format organized like a tree

This question has been asked before, but no one seems to have answered yet. Imagine a scenario where a MySQL query returns results like this: name | id tarun | 1 tarun | 2 tarun | 3 If we were to standardize the JSON encoding, it would l ...

Is it possible for the 'error' attribute to be deemed invalid or inappropriate within ajax?

I am encountering an issue with my mobile cordova application. When attempting to log in, I am facing the following error: Error: JavaScript runtime error - Object doesn't support property or method 'error' The error is being traced back t ...

Converting Integers to Integers in Javascript: A Step-by-Step

Let's say I have a Method written in JavaScript in GWT(JSNI) which accepts the wrapper data type Integer and I need to convert it into a Primitive Data type inside JS. public static native void nativeMethod(Integer index)/*-{ // What is the best ...

Having trouble with the functionality of the jQuery `has()` method?

Consider the following HTML code snippet: <div class="comment"> <span class="test">some content here</span> <p>Lorem ipsum</p> </div> <div class="comment"> <p>Lorem ipsum</p> </div> The ob ...

What is the best way to send an HTTP request in AngularJS to receive data in JSON format?

I am trying to create an AngularJS app that can send HTTP requests for JSON data. I have written the code in my index.html file to request JSON data using AngularJS, but for some reason, the JSON data is not being printed. When I check the console in Fire ...

Preventing or deleting local cache when sending a canvas blob through AJAX requests

I am sending a canvas image to my server via AJAX using the following method: myCanvas.toBlob( function( blob ) { var fdata = new FormData( ); fdata.append( 'myFile', blob ); $.ajax( { url: 'http://myScript.foo', ...