How can I retrieve elements from an array that match a certain criteria and update the corresponding objects in

When an array contains matching IDs, the goal is to merge these objects into one object without affecting the original array. The current code only returns matching objects, but the expected result should combine them as described.

main.ts

const arr = [{
            "body": {
                "specialtyID": "7114798",
                "sourceSystem": "HBS",
                "rxInfos": [{
                    "drugNdc": "00445450085",
                    "rxNumber": "14678904"
                }]

            },
            {
                "body": {
                    "specialtyID": "7114798",
                    "sourceSystem": "HBS",
                    "rxInfos": [{
                        "drugNdc": "00004080085",
                        "rxNumber": "1459004"
                    }]
                }
            },
            {
                "body": {
                    "specialtyID": "7908398",
                    "sourceSystem": "HBS",
                    "rxInfos": [{
                        "drugNdc": "06789955085",
                        "rxNumber": "1478604"
                    }]
                }
            }

        ]


        const tempArray = arr;

        function arrayMatch(temp, arr) {
            const finalArray = [];
            arr.forEach((element) => {
                    tempArray.forEach((temp) => {
                            if (temp.speicaltyID === element.specialtyID) {
                                temp.rxInfos.forEach((rxInfo) => {
                                    element.rxInfos.push(rxInfo);
                                });
                            }
                        }
                        finalArray = arr;

                    });
                return finalArray

            }

expected output

 const arr = [{
                        "body": {
                            "specialtyID": "7114798",
                            "sourceSystem": "HBS",
                            "rxInfos": [{
                                    "drugNdc": "00445450085",
                                    "rxNumber": "14678904"
                                },
                                {
                                    "drugNdc": "00004080085",
                                    "rxNumber": "1459004"
                                }
                            ]
                        },
                        {
                            "body": {
                                "specialtyID": "7908398",
                                "sourceSystem": "HBS",
                                "rxInfos": [{
                                    "drugNdc": "06789955085",
                                    "rxNumber": "1478604"
                                }]
                            }
                        }

                    ]

Answer №1

For the desired outcome, you can experiment with the following approach:

const result = arr.reduce((container, value) => {
    const compare     = ({ data }) => data.id === value.data.id;
    const isPresent   = container.some(compare);
    const mergeData   = container.map(item => compare(item) ? item.data.list.push(...value.data.list) : item);

    isPresent ? mergeData : container.push(value);

    return container;
}, []);

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

Utilize the filtering feature within the Vue select module

I'm struggling to get the select filter to work properly in my Quasar application. When I open the select, there is no list displayed and no value gets selected. Can someone help me understand why it's not working? <q-select v-mo ...

Does AngularJS have a callback function for ng-bind-html-unsafe?

Is there a way to efficiently remove certain elements from the DOM after they have been added by this code snippet? <div ng-bind-html-unsafe="whatever"></div> I have created a function to remove these elements, but I am unsure how to trigger ...

Unable to locate a declaration file for the 'mymodule' module

After attempting to import my test module by installing it with npm i github.com/.../..., the code is functioning properly. However, when I opened it in VSCode, an error message popped up: Could not find a declaration file for module 'estrajs'. & ...

The canvas doesn't seem to be rotating even after executing the setTransform

Within my HTML5 canvas, I have been experimenting with drawing lines and rotating them around the center point. My goal is to reset the canvas's transformation each time I draw, followed by re-translating/rotating the canvas. However, I have encounter ...

Unit tests are being blocked by the constructor of an Angular service

I'm currently struggling with writing unit tests for a service that performs some actions in its constructor. This is causing issues in my tests and I'm unsure how to handle it :( Here is the service class: import { Injectable } from '@a ...

Is it possible to modify a single value in a React useState holding an object while assigning a new value to the others?

In my current state, I have the following setup: const [clickColumn, setClickColumn] = useState({ name: 0, tasks: 0, partner: 0, riskFactor: 0, legalForm: 0, foundationYear: 0 }) Consider this scenario where I only want to update ...

How can I trigger a masterpage function from a contentpage in asp.net?

I am trying to call a function on the masterpage from a content page in the codebehind. Here is my attempt: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert__", string.Format("setStatusBarMessage('{0}',{1});", barMessage, ty ...

What is the best way to retrieve an array that was created using the useEffect hook in React?

Utilizing the power of useEffect, I am fetching data from two different APIs to build an array. My goal is to access this array outside of useEffect and utilize it in the return statement below to render points on a map. However, when trying to access it ...

Updating a data attribute in Angular 2: A different approach

Currently, I am utilizing ConvertFlow to integrate pre-designed form templates into my project. To specify where the form should appear, I include a div with the unique identifier of the form created within their platform. While this process is straightfor ...

Form submission using AJAX is either limited to one-time use or requires a page refresh to update

One of the challenges I encountered while working on a wiki app built in Rails was updating a table of collaborators using JavaScript. I wanted to add collaborators from an existing users' table without having to refresh the page every time. Initially ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

Initiate the function once the condition is satisfied (contains the class "in-view")

Here is the code for an animation: var setInter = null; function startAnimation() { var frames = document.getElementById("animation").children; var frameCount = frames.length; var i = 0; setInter = setInterval(function () { fr ...

Display Error with Custom Alert Box

I recently implemented a customized alert box from slayeroffice's website, which you can find at slayeroffice.com/code/custom_alert/. When I view it on my browser, the alert box appears with a blue color in the center of the screen. Here is how it lo ...

Unexpected output from the MongoDB mapReduce function

Having 100 documents stored in my mongoDB, I am facing the challenge of identifying and grouping possible duplicate records based on different conditions such as first name & last name, email, and mobile phone. To achieve this, I am utilizing mapReduc ...

Set the root of Ionic OneSignal Push Notification instead of pushing it from the Home page to Another Page

Experiencing some trouble with my OneSignal push notifications and page redirection. While the app is open, tapping on a notification pushes the news-detail page onto the stack from the current home page. (This behavior is desired when the app is closed.) ...

Adjusting canvas dimensions for angular chart.js: A quick guide

I am currently creating my first sample code using angular chart.js, but I am facing an issue with changing the custom height and width of my canvas. How can I adjust the height and width accordingly? CODE: CSS #myChart{ width:500px; he ...

VueRouter child route with trailing slash after default

VueRouter automatically includes a trailing slash before the child route's path. Consider this example of a route configuration: const routes = [ path: '/home', components: { default: HomeBase }, children: [ ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

What is the correct way to use setInterval in a React component's constructor?

I'm trying to set an interval when the main component renders. I attempted to do this in the constructor like so: constructor(props) { super(props); this.props.fetchUserInfo(); this.props.fetchProducts(); setInterval(console.log(&a ...

What is the best way to iterate over a nested array of objects and render them in my HTML using Angular/Ionic?

One of the challenges I'm facing involves working with an interface structured like this: export interface SeriesCard { type: string, imageUrl: string, title: string, category: string, seriesItems: SeriesItems[]; } Currently, my Service con ...