Is there a way to merge two arrays with a specific condition?

I need to update the state in one array based on the values of another array. The goal is to include all statuses from the second array into the first without any duplicates. However, the provided sample code is not comprehensive.

const arr1 = [{ agentId: 1234, state: "CA" }];
  const arr2 = [{ agentId: 1234, AK: "c", AL: "N", CA: "c" }];
  var res = [];
  arr1.forEach((x) => {
    arr2.forEach((y) => {
      if (x.agentId === y.agentId) {
        for (const [key, value] of Object.entries(y)) {
          if (value === "c") {
            x.state += " ," + key;
          }
        }
      }
    });
  });

The desired output should be as follows:

arr1 = [{ agentId: 1234, state: "CA, AK" }]

Answer №1

One way to find a matching agentId using Array.reduce and Array.find is by combining two arrays like this:

const firstArray = [{ agentId: 1234, state: "CA" }];
const secondArray = [{ agentId: 1234, AK: "c", AL: "N", CA: "c" }];

const combinedArray = firstArray.reduce( (accumulator, value) => {
  const matchedValue = secondArray.find(elem => elem.agentId === value.agentId);
  if(matchedValue) {
    return [...accumulator, {...value, ...matchedValue} ];
  }
  return accumulator;
}, []);

console.log(combinedArray);

Answer №2

To achieve uniqueness, you can utilize a Set:

const arr1 = [
  { agentId: 1234, state: "CA" },
  { agentId: 4567, state: "FL" }
];
const arr2 = [
  { agentId: 1234, AK: "c", AL: "N", CA: "c" },
  { agentId: 4567, AK: "N", AL: "c", FL: "c" }
];

for (const x of arr1) {
  const states = new Set([x.state]);
  for (const y of arr2) {
    if (x.agentId === y.agentId) {
      for (const [key, value] of Object.entries(y)) {
        if (value === "c") {
          states.add(key);
        }
      }
      break;
    }
  }
  x.state = [...states].join(", ");
}

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

When there is a lack of internet connection, WKWebView does not reach completion or timeout

When using a WKWebView to navigate to a local HTML page, I encountered an issue with a remote Javascript asset tag that never finished downloading. This occurred even when the iOS device was not connected to the internet or had slow internet speeds. The p ...

Testing Ajax code encounters error

Currently, I am running a code test with Jasmine and setting up a mock object for the ajax method. spyOn($,'ajax').and.callFake(function(e){ console.log("is hitting"); }) In order to test the code snippet below: $.ajax({ url: Ap ...

What is the process for ordering by a many-to-many relationship in Sequelize?

I am dealing with a many-to-many relationship between User and Category, connected through the UserCategory model. Here is the code snippet illustrating this relationship: let user = await User.findAll({ where: { id: req.query.user }, attribut ...

Is it possible to overlay color on top of a div background? (i.e. modify div color without altering the 'background-color' property)

Can you apply a color "on top of" a div's background? I'm looking to change the displayed color of a div without altering the 'background-color' value. I need to keep the background-color for comparison when divs are clicked: var pick ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

Instructions for downloading a .zip file sent through a HTTP response (using an axios PUT request)

When the API responds, it should contain a data property with the .zip file I need. However, the format is unfamiliar to me. The format: https://i.sstatic.net/ruaVR.png I attempted to use .blob() as suggested in similar questions on Stackoverflow, but it ...

Get a PDF file from MongoDB via jade Template Engine

Currently, I am utilizing Node, along with express, Jade, and a MongoDB to query the database and showcase the data on a webpage. Within the database, PDFs are stored and my goal is to enable users to download these files directly from the webpage. While ...

What is the best way to link a generated PHP-AJAX link with a jQuery action?

Imagine a scenario like this: trollindex.htm: [...] <script> $(document).ready(function(){ $("* a.jquery").on("click",function(){ $.ajax({ type: "POST", url: "trollcommander.php", data: ({comman ...

Tips for creating clickable selections with AutoComplete JQuery in ASP.NET and C#

Currently, I am working on a project that involves implementing AutoComplete functionality in a textbox using JQuery AutoComplete. I have included the following file: jquery-ui.js The goal is to make the matched text appear in bold. For example, if I typ ...

"Email verification is always set to true for users signing in through Firebase

Currently, I am working on integrating a sign-in form using Firebase web and Vue.js. The issue I'm facing is that I need to send a verification email to confirm the user's email address, but the emailVerified key is always set to true by default ...

Body-Processing Protocol

When I send a cURL POST request, it looks like this: curl http://tarvos.local:8080/partial_Users/2 -d '{currentPage : 1, firstID : 53d62fc6642aecf45c8b456f }' Within my NodeJS application, the request passes through the bodyParser.json() middl ...

Changing the color of a text box when it is disabled can be achieved through JavaScript

I'm facing an issue with the formatting of my HTML elements. Specifically, I have 2 combo boxes and one text box in which all 3 are disabled. However, when they are disabled, the background color of the text box does not match that of the combo boxes. ...

Unable to show <LI> elements

I'm having trouble adding LI items to the #historial <UL> tag. Whenever the for loop is inside the function, the list displays with some elements duplicated. I believe the for loop should remain outside of the function. Could someone please he ...

Custom CSS for the Google Maps Circle Object

Currently, I am utilizing the Google Maps Javascript API v3 Circle object to display circles on the map. I am interested in customizing the CSS of this circle by incorporating some CSS animations. Although I am aware that custom overlays can be used for t ...

Creating a list repeater using v-for in Vue.js 2 with computed property

Seeking assistance with adding computed columns to a table (last three columns). Suspecting the issue lies in the computed property not correctly referencing the record. Any simple solutions that I might be overlooking? Appreciate any thoughts or insights! ...

How to send a global variable to an event callback function in JavaScript?

I have encountered an issue in the following code where I am attempting to pass mydata to the callback function. This is just a small part of a larger problem that I am facing and I suspect it may be related to scope. Can anyone help me identify what is wr ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

What is the significance of using parentheses around a function in JavaScript?

Currently, I am developing an application using Java and JavaScript, and while reviewing some code today, I came across a segment that seemed confusing to me. var myVariable = (function(configObj){ var width = configObj.width; var height = config ...

Attempting to access a shared php/javascript library using mod_rewrite

Let's dive into a fresh perspective on a question I previously raised: I've crafted a mod_rewrite snippet that checks for the existence of JavaScript, CSS, and PHP files on the subdomain they are called from (e.g., subdomain.example.com). If the ...

Having issues with importing images in Next.js using the Next Images package

Having trouble with importing images locally from the images folder. Error message: "Module not found: Can't resolve '../images/banner1.jpg'" https://i.stack.imgur.com/Dv90J.png Attempting to access images in ImagesSlider.js file at compo ...