Contrast the equality of two arrays with objects

I have two different types of data structures

   var dataA = [
  {
    "Employee Name": "Mr. X",
    id: "1"
  },
  {
    "Employee Name": "Mr. Y",
    id: "2"
  },
  {
    "Employee Name": "Mr. Z",
    id: "3"
  }
];

var dataB = [
  {
    id: "1",
    "Portfolio Lead": "A"
  },
  {
    id: "2",
    "Portfolio Lead": "B"
  },
  {
    id: "4",
    "Portfolio Lead": "D"
  }
];

My goal is to compare the id values of both arrays and include the "Portfolio Lead" property in dataA.

Here is my current method,

function mergeTwoArray() {
  dataA.forEach(row => {
    dataB.forEach(lead => {
      if (lead["id"] === row["id"]) {
        row["Portfolio Lead"] = lead["Portfolio Lead"];
      }
    });
  });
  console.log(dataA);
}

The issue I'm facing is that when the id does not match, I want to add "#NA" as the value for "Portfolio Lead". However, including an if statement results in all objects having "Portfolio Lead" set to #NA.

If you can help point out what I'm doing wrong here, I would greatly appreciate it.

For a live example, please refer to this stackBlitz link https://stackblitz.com/edit/typescript-nypqge?file=index.ts

The desired output should be:

var dataA = [
  {
    "Employee Name": "Mr. X",
    id: "1",
    "Portfolio Lead": "A"
  },
  {
    "Employee Name": "Mr. Y",
    id: "2",
    "Portfolio Lead": "B"
  },
  {
    "Employee Name": "Mr. Z",
    id: "3",
    "Portfolio Lead": "#NA"
  }
];

Answer №1

To ensure a match has occurred, simply introduce a boolean condition. In cases where no match is found, proceed to set the object property to "#NA".

function combineArrays() {
  datasetA.forEach(entry => {
    var entryMatches = false;
    datasetB.forEach(record => {
      if (record["id"] === entry["id"]) {
        entryMatches = true;
        entry["Lead Name"] = record["Lead Name"];
      }
    });
    if (!entryMatches) {
      entry["Lead Name"] = "#NA";
    }
  });
  console.log(datasetA);
}

Answer №2

If you're looking to merge two arrays, give this a shot:

function mergeArrays() {
  array1.forEach(item => {
    let index = array2.findIndex((element) => element["id"] == item["id"]);

    if (index >= 0) {
      item["name"] = array2[index]["name"];
    } else {
      item["name"] = "#NA";
    }
  });
  console.log(array1);
}

Answer №3

To include an else if statement, you can do the following:

else if(row["id"] > lead["id"]){
    row["Portfolio Lead"] = "#NA";
}

The reason why row["Portfolio Lead"] = "#NA"; is placed in the else block is because it gets executed for every iteration of the outer loop due to the inner loop running through the length of dataB each time. This means that the code is checking if the id of the outer loop is greater than the id of the inner loop before updating.

Your updated code should now look like this:

dataA.forEach(row => {
  dataB.forEach(lead => {
    if (lead["id"] === row["id"]) {
      row["Portfolio Lead"] = lead["Portfolio Lead"];
    } else if(row["id"] > lead["id"]){
      row["Portfolio Lead"] = "#NA";
    }
  });
});

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

Verify the Javascript for file upload in ASP.NET folder prior to uploading it

Struggling with this problem for days now, I could really use some fresh perspective. My setup includes Windows Server 2012, IIS 8.0, and ASP.NET 4.5. I'm new to both IIS and ASP.NET, so please bear with me. The website I'm working on involves f ...

The value of req.file is not defined by multer

I'm at my wit's end with this issue. Despite searching extensively, none of the proposed solutions have resolved it for me. I am attempting to set up a basic file upload using multer, but I cannot seem to make it work as req.file consistently rem ...

Having trouble obtaining a GuildMember's displayName in Discord.js leads to a TypeError

I'm completely baffled by the situation here. My code is integrated within the Akairo Framework, yet the error seems to be pointing fingers at discord.js itself. Take a look at the error message below: /home/runner/guard/Listeners/automod/nicknames.js ...

Using Express.js to transform req.body into a POST encoded string

I need to convert the req.body object into a POST encoded string using the express.bodyParser middleware. Is there a way to achieve this? For example: Name: Jane Doe Age: 30 City: Los Angeles Should become: Name=Jane+Doe&Age=30&City=Los+Angeles ...

exploring an array using boolean conditions

Seeking assistance as a beginner with creating a boolean search function in my AccountCollection class. The goal is to print a single account based on the account number provided, using a method from the Account class. If the account number is invalid, it ...

Is it necessary to implement ngOnDestroy for subjects in Angular?

Is it necessary to manually unsubscribe using the ngOnDestroy hook when using the subject in Angular, or does Angular handle the unsubscribing automatically? ...

Guide on invoking setImmediate prior to or above .on('data') in fast-csv using Node.js

I'm currently utilizing fast-csv (https://www.npmjs.com/package/fast-csv) for parsing a csv file. The file could possibly contain 10k records, leading to significant delays in parsing and blocking other operations on the server. To address this issu ...

Extracting IDE autocomplete in a Vue.js component can greatly improve your workflow and efficiency

Currently, I am in the process of developing a component library for the organization where I work. To achieve this, I am utilizing vuetify in combination with vue.js. One of the tasks at hand is to create custom components such as company-autocomplete, w ...

Verify whether the input field contains a value in order to change certain classes

My meteor-app includes an input field that dynamically changes position based on whether it contains content or not. When a user begins typing, with at least one character, the input field moves to the top of the page. In my current approach, I am using a ...

This element is not compatible for use as a JSX component

I have created a React component which looks like this import React from 'react'; import { ECOTileSummary } from './ECOTileSummary'; import { TileSummary } from './TileSummary'; interface SuperTileSummaryProps { date?: s ...

The code snippet for adding a class using jQuery with $(this) seems to be malfunctioning, and

I'm facing an issue with this code, it's supposed to add a class when clicked on but it's not working. $('a').click(function(){ //alert('on'); WORKING $(this).addClass('on'); }) The HTM ...

Upon initial startup, the "Get Authenticated" process gets stuck in an endless loop

Upon initially loading my AngularJS application, I am faced with a blank screen and an endless loop attempting to verify the user's authentication status. For this specific project, I have opted for sails version 0.11.0 as well as the latest version ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...

AngularJs does not properly update the scope of a scoped directive when using ng-repeat within itself

The issue arises from calling Directive1 within the same Directive1 using ng-repeat. Although directive11 has a value in scope, when calling the nested directive with a new value, it appears to retain the initial value. I attempted to invoke the same dire ...

Make a call to a URL in Symfony2 with JavaScript (AJAX)

I have developed a Symfony2 RESTful webservice prototype that is still a work in progress. I am looking for guidance on how clients can send JSON data or consume JSON data from this webservice. Essentially, I need examples of how to send requests or post d ...

jQuery: Eliminating Parent Elements

Currently, I am developing a small web application that allows users to create lists which are then formatted and emailed to them. However, I am facing difficulties in implementing a method that will allow users to delete list items without clearing the en ...

Transform **kerry James O'keeffe-martin** into **Kerry James O'Keeffe-Martin** using TypeScript and Java Script

Is there a way to capitalize names in both TypeScript and JavaScript? For example, changing kerry James O'keeffe-martin to Kerry James O'Keeffe-Martin. ...

What is the best way to incorporate tailored validation into reactive forms in Angular?

I'm facing an issue with my form where I'm trying to display a specific error message based on certain conditions. Currently, my form is functioning but it's throwing a type error stating "undefined is not an object". I'm struggling to ...