Guide on combining two arrays of similar objects and performing operations on a specific field within them

I am faced with a scenario where I have two arrays of objects with identical structures. Array 1 consists of elements like:

[
        {
            id: "1",
            name: "XX",
            displayName: "XX",
            count: 12
        },
        {
            id: "2",
            name: "XX",
            displayName: "XX",
            count: 12
        },
        {
            id: "3",
            name: "XX",
            displayName: "XX",
            count: 12
        }
    ]

Meanwhile, Array 2 contains elements as follows:

[
        {
            id: "1",
            count: 2
        },
        {
            id: "3",
            count: 5
        }
    ]

My goal is to create a new array with the same structure as Array 1, but with adjusted count values. The desired output should look like this:

[
        {
            id: "1",
            name: "XX",
            displayName: "XX",
            count: 10
        },
        {
            id: "2",
            name: "XX",
            displayName: "XX",
            count: 12
        },
        {
            id: "3",
            name: "XX",
            displayName: "XX",
            count: 7
        }
    ]

This means that if a matching ID is found in Array 2, the new count should reflect the difference between the two values. Otherwise, the count remains unchanged. I have attempted to solve this using the .reduce() method, but I am struggling with the logic. As I am relatively new to JavaScript, coming from a background in C99 and Python, I am seeking guidance on how to approach this problem.

I am avoiding the use of nested for loops for efficiency reasons. One potential solution I considered was to convert all count values in Array 2 to negative, and utilize a method I discovered on the same website. This method involves summing up integer attributes:

        const sumItem = ({ id, ...a }, b) => ({
            id,
            ...Object.keys(a)
                .reduce((r, k) => ({ ...r, [k]: a[k] + b[k] }), {})
            });
        

        const sumObjectsByKey = (...arrs) => [...
            [].concat(...arrs) // combine the arrays
                .reduce((m, o) => // reduce the combined arrays to a Map
                    m.set(o.id, // add the item to the Map
                        m.has(o.id) ? subItem(m.get(o.id), o) : { ...o } // if the item exists in the Map, sum the current item with the one in the Map. If not, add a clone of the current item to the Map
                    )
                    , new Map).values()]

However, this approach does not feel elegant or optimal, and I believe I should focus on improving my understanding of map-related methods. Can anyone provide assistance with this issue?

Answer №1

Utilize the Reduce method to transform into an intermediary object and extract the values from it:

const array1 = [{
  id: "1",
  name: "XX",
  displayName: "XX",
  count: 12
}, {
  id: "2",
  name: "XX",
  displayName: "XX",
  count: 12
}, {
  id: "3",
  name: "XX",
  displayName: "XX",
  count: 12
}];

const array2 = [{
  id: "1",
  count: 2
}, {
  id: "3",
  count: 5
}];

const result = Object.values([...array1, ...array2].reduce((a, v) => {
  if (a[v.id]) a[v.id].count -= v.count
  else a[v.id] = { ...v }
  return a;
}, {}));

console.log(result);

Answer №2

One approach involves using the Array#map method to update the array counts and utilizing Array#find to locate the corresponding element by id from the second array during each iteration.

let arr1=[{id:"1",name:"XX",displayName:"XX",count:12},{id:"2",name:"XX",displayName:"XX",count:12},{id:"3",name:"XX",displayName:"XX",count:12}],
    arr2=[{id:"1",count:2},{id:"3",count:5}];
let res = arr1.map(o => ({...o, count : o.count - 
  (arr2.find(x => o.id === x.id)?.count ?? 0)}));
console.log(res);

Another more efficient strategy involves initially creating an object that maps each id in the second array to its respective count, which can then be used when generating the new array.

let arr1=[{id:"1",name:"XX",displayName:"XX",count:12},{id:"2",name:"XX",displayName:"XX",count:12},{id:"3",name:"XX",displayName:"XX",count:12}],
    arr2=[{id:"1",count:2},{id:"3",count:5}];
let counts2 = arr2.reduce((acc, curr) => {
  acc[curr.id] = curr.count;
  return acc;
}, {});
let res = arr1.map(o => ({...o, count : o.count - (counts2[o.id] ?? 0)}));
console.log(res);

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

A guide to integrating ffmpeg with NuxtJS

I am completely new to Nuxt and currently in the process of migrating a Vue application that generates gifs using ffmpeg.wasm over to Nuxt.js. However, every time I try to access the page, the server crashes with the following error message: [fferr] reques ...

Utilize React to dynamically load diverse data arrays into a slick slider component

I am currently working on a component that includes a slider displaying photos linked to different rooms. The next step is to move this slider to a separate page or component, which will display content for rooms, news, and promotions using different arr ...

What causes the alignment of text to be overridden by the presence of a floating element?

https://jsfiddle.net/u0Ltgh3e/68/ .text { width: 50%; text-align: justify; } I am currently developing a custom formatting tool for a specific purpose and I am attempting to create a two-column layout similar to the one demonstrated in this Jsfiddle l ...

Why does my JavaScript only trigger my web service request when I set a breakpoint?

Can you help me understand why my JavaScript code only calls my webservice when I set a breakpoint on the line ].getJSON, but not if I remove the breakpoint? $(function () { $("#" + @Model.BidObjectId).submit(function () { ale ...

What methods can be used to control access to document.styleSheets data, and what is the purpose behind doing so?

Recently, I came across the document.styleSheets API, which allows you to access stylesheets used by a website. Using this API is simple, for example, document.styleSheets[0].cssRules will provide all CSS rules for the first stylesheet on a page. When I t ...

Struggling to reveal concealed items on a webpage using jQuery and attempting to cycle through an array without success

Looking to display or hide certain sections on a page based on specific conditions. I want to only show the sections of the page that contain words from the conditionsToShow array. function hideWorkflowConditions() { // initially hide the elements ...

Tips for preventing useEffect from triggering a route?

Recently delving into reactjs, I stumbled upon a situation in the code where the route alerts messages twice. I'm seeking advice on how to prevent this issue, please disregard the redux code involved. Any suggestions? Index.js import React from &apos ...

Having trouble with sending an AJAX request to a different domain?

I've been attempting to utilize the following API: However, upon making an AJAX call, I encounter this specific error: XMLHttpRequest cannot load /radius.json/30341/10/mile. No 'Access-Control-Allow-Origin' header is present on ...

Determine the sequence of a div based on its class

Here is the code snippet I am working with: <div class="test"></div> <div class="test"></div> <div class="test"></div> <input type="button" class="button" value="get number"> <div class="test"></div> & ...

"Encountering a problem when trying to display Swagger-Editor for the second

While integrating the swagger-editor package into my React application, I encountered an issue. The first time I fetch the Swagger specifications from GitHub, everything works perfectly and validates correctly. However, upon rendering it a second time, an ...

"Enhancing user experience with React.js and Socket.io: dynamically updating list item positions based on

export default class ReactApp extends React.Component { constructor(props) { super(props) this.state = { status: [], services: [] } fetchData((err,opt, data) => { function Exists(l ...

Unable to execute two functions consecutively

After running the code, I encountered the error message Uncaught TypeError: object is not a function and only the status function is working properly. Can anyone help me identify the issue? $(document).ready(function() { steam('status', 60 ...

Begin 5 seconds after loading

First time attempting this task. My goal is to trigger the loading of an I have been trying to write a script for this, but it's not functioning as expected. HTML : <div id="div1"> <a id="single" href="#">Single Play</a> & ...

The browser prevented the script located at “http://127.0.0.1:5500/assets/platform.png” from loading due to an invalid MIME type of “image/png”

Sorry if this question seems repetitive, but despite extensive searching, I haven't been able to find a solution to my specific problem. I am currently working on developing a basic JavaScript game, but I'm facing challenges when it comes to impo ...

`Inquiry into AJAX form submission problem`

Here is the HTML markup and JS code for my signup page. I encountered an issue where, if I leave all text inputs blank and click submit for the first time, it validates and shows an error message. However, when I click submit a second time, it directly sen ...

Steps to simulate a TouchEvent programmatically using TypeScript

Is there a way to manually trigger the touch event in TypeScript? In JavaScript, it was possible but I am struggling to achieve the same in TypeScript. For example: let touchStart: TouchEvent = document.createEvent('TouchEvent'); touchStart.i ...

jQuery AJAX is seamlessly handling cross domain requests in Chrome and other browsers, however, it seems to be struggling in IE10 as it is not properly transmitting data. Additionally, in Internet

My web application requires sending data to an API hosted on a different domain. The API processes the received data and jQuery AJAX handles the response. This process works smoothly on Chrome and Firefox, but encounters issues on Internet Explorer. While ...

Exploring ways to retrieve elements from a subarray in Java using indexes instead of keys

Looking at a JSON structure: { "Message": "None", "PDFS": [ [ "test.pdf", "localhost/", "777" ], [ "retest.pdf", "localhost\", "666" ] ], "Success": true } An attempt ...

Conceal the complete <div> in the event that the <table> contains no data

My task involves managing a div containing a table. The goal is to hide the div if it has no value or is empty, and then show it again once it has a value. <div class="container" id="main_container"> <table id="my_tabl ...

How can we effectively implement alert notifications for validating image sizes and formats prior to uploading?

code playground : https://codesandbox.io/s/quizzical-lamport-ql5ep I'm encountering an issue with the code provided in the CodeSandbox link. https://i.sstatic.net/xg3aK.png I've attempted to resolve this issue using various methods, but unfortu ...