Evaluating two arrays and adding elements if the criteria are satisfied

In my attempt to filter out emails that already exist in the userData, the current issue is that my code continuously adds the same data as long as the email is not the same.

Below is the code snippet:

userData:[ {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="791318171c571d161c3914181015571a1614">[email protected]</a>", 
           first_name: "Jane", 
           last_name: "Doe"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c76737472327873795c6f7d716c7079327f7371">[email protected]</a>", 
           first_name: "john", 
           last_name: "doe"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd1ddcec5e3d6ddd2d9fcd1ddd5d092dfd3d1">[email protected]</a>", 
           first_name: "Mary", 
           last_name: "Jane"}
],
parseData:[ {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa909b949fd49e959fba979b9396d4999597">[email protected]</a>", 
           first_name: "Jane", 
           last_name: "Doe"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e745156505047617c4c5f48517e4d5f534e525b105d5153">[email protected]</a>", 
           first_name: "Johnny", 
           last_name: "Bravo"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="feb49f878d9190d0bf9c8b9b929fbe939f9792d09d9193">[email protected]</a>", 
           first_name: "Jayson", 
           last_name: "Abuela"}
],
newData: []

var userData = this.userData
var parsedData = this.parseData
function(results) {
            const parsedData = results.data
            for(var j = 0; j < parsedData.length; j++){
              userData.map((data)=>{
                  if(data.email.toLowerCase() != parseData[j].email.toLowerCase()){
                    newData.push(parsedData[j])
                    
                  }else{
                     alert("This "+parsedData[j].email+" already exist.")
                   }
              })
            }
          }

The expected behavior is to have the user with email of

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="672d080f09091e3825150611082714060a170b024904080a">[email protected]</a>
and
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a200b13190504442b081f0f060b2a070b030644090507">[email protected]</a>
pushed into my newData only once, but currently each data gets pushed multiple times.

Answer №1

Wouldn't it be easier to do it the straightforward way?

const userData = [ {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e3e8e7eca7ede6ecc9e4e8e0e5a7eae6e4">[email protected]</a>", 
           first_name: "Jane", 
           last_name: "Doe"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc7c2c5c383c9c2c8eddeccf0ddc1c883cec2c0">[email protected]</a>", 
           first_name: "john", 
           last_name: "doe"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e535f4c4761545f505b7e535f5752105d5153">[email protected]</a>", 
           first_name: "Mary", 
           last_name: "Jane"}
];

const parseData = [ {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bf1faf5feb5fff4fedbf6faf2f7b5f8f4f6">[email protected]</a>", 
           first_name: "Jane", 
           last_name: "Doe"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d79db8bfb9b9ae8895a5b6a1b897a4b6baa7bbb2f9b4b8ba">[email protected]</a>", 
           first_name: "Johnny", 
           last_name: "Bravo"}, 
           {email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e0aa8199938f8ecea18295858c81a08d81898cce838f8d">[email protected]</a>", 
           first_name: "Jayson", 
           last_name: "Abuela"}
];

const tempEmails = userData.map(x => x.email.toLowerCase());
const newEmails = parseData.filter(x => !tempEmails.includes(x.email.toLowerCase()));

console.log(newEmails);

Unable to determine the preferred arrangement. You can easily switch parseData and userData if needed.

Edit: These are known as lambda functions, simple and useful. Utilizing map() to generate an array of email strings. Then using filter() to compare each object's email key with the initial array of email strings and exclude the matching ones. Straightforward approach.

Answer №2

Your current code doesn't verify if the email already exists in the other array. It simply compares the email with each element of the array and adds it if it doesn't match.

To improve this, you can create a Set that contains all the emails from the parsedData array. This way, you can easily check if the email already exists using the .has() method.

const parsedDataSet = new Set(parsedData.map(({email}) => email.toLowerCase());
userData.forEach(u => {
    if (!parsedDataSet.has(u.email.toLowerCase())) {
        parsedData.push(u);
        parsedDataSet.add(u.email.toLowerCase());
    }
);

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 is the best way to organize a json based on numerical values?

Can anyone guide me through sorting a JSON data into an array based on numeric value, and then explain how to efficiently access that information? {"362439239671087109":{"coins":19},"178538363954003968":{"coins":18},"234255082345070592":{"coins":137}} Th ...

Angular UI-Select's issue with duplicating tags while adding objects for tagging functionality

I have implemented the ui-select library to enable the "Tagging" feature in my project. Currently, I am utilizing an Array of objects where each object contains an id and a name. The functionality is working as expected. However, when a user types in a n ...

Incorporate various Vue.js components into the main parent component

I am currently utilizing Vue.js to create a user interface for my HTML5 game. I have a scenario where I want to define UI containers that essentially group other UI components and position them on the screen. Here's an example of what I'd like to ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

What are the steps to configure MongoDB on Heroku using MongoHQ and Node.js?

I am currently using a local application, which is what I'm most familiar with. Heroku provided the following snippet of code: var mongo = require('mongodb'); var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || &apos ...

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

Is jQuery utilized by the bootstrap-grid system?

Finale: In our current setup, we are utilizing Angular 9, and like many frontend frameworks, there is a preference against incorporating other JavaScript libraries alongside the framework for manipulating the DOM. The Challenge: I am hesitant to include ...

Error: Attempting to access the 'name' property of an undefined variable is resulting in a TypeError in Material UI

When attempting to display the retrieved data on MUI Autocomplete, I encountered an error that I cannot seem to figure out. The data is fetched from MongoDB, and I simply want to showcase the category names as selectable options. https://i.sstatic.net/cxT ...

JavaScript: Controlling the ability to enter text based on the chosen option from a drop-down menu

After struggling to make my code work, I decided to create a piece of JavaScript to disable a text input when "Cash" payment is selected from the dropdown menu. On the contrary, I aimed to enable the text input if "Credit Card" payment was chosen. Unfortun ...

What steps can be taken once the browser has completed all rendering processes?

I have a large form that functions on older PCs. This form is a component of a thin client system and is implemented using AngularJS to create a Single Page Application. One of the tabs on the SPA includes this form. Upon opening the form, requests are se ...

Next.js App experiences a 404 Error when attempting to access the Auth0 Endpoint "api/auth/me"

Following a tutorial, I integrated my Next.js App with Auth0 successfully. However, after logging in and out, I encountered an issue where the user object is not returned when trying to display user information on the page post-login. Both the Profile.js p ...

Numerous checkboxes have been chosen alongside a submission button

I recently completed a small project involving multiple checkboxes using ajax. You can view the demo here. However, I am now looking to implement a submit button for filtering options. After selecting multiple checkboxes and clicking the submit button, onl ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

What is the reason that when the allowfullscreen attribute of an iframe is set, it doesn't appear to be retained?

Within my code, I am configuring the allowfullscreen attribute for an iframe enclosed in SkyLight, which is a npm module designed for modal views in react.js <SkyLight dialogStyles={myBigGreenDialog} hideOnOverlayClicked ref="simpleDialog"> <if ...

Why isn't my watch function functioning properly within Vue?

In my JS file, I have two components. The file starts with this line: const EventBus = new Vue(); I am trying to pass two strings, 'username' and 'password', from the first component to the second component, but it's not working. ...

storing a value in the browser's local storage

I am in the process of creating a new game that includes a high score feature. The idea is that when the current score surpasses the existing one stored locally, it will be replaced: localStorage.setItem('highScore', highScore); var HighScore = ...

Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's perm ...

When working with create-react-app and TypeScript, you may encounter an error stating: "JSX expressions in 'file_name.tsx' must

After setting up a React project with TypeScript using the CLI command create-react-app client --typescript, I encountered a compilation error when running npm start: ./src/App.js Line 26:13: 'React' must be in scope when using JSX react/r ...

Working with Node.js and JavaScript's Date object to retrieve the time prior to a certain number of hours

I am currently working on a script in node.js that is able to locate all files within a specific directory and retrieves their modified time: fs.stat(path, function(err, states){ console.log(states.mtime) }) After running the script, it ...

"Error: Discord Js encounters an issue trying to access the titles property of an

Having trouble with a random number generator in my discord bot. Whenever someone enters +nhr, it may work or display an error message in the console: TypeError: Cannot read property 'titles' of undefined and Unhandled promise rejection. Thi ...