Is foreach not iterating through the elements properly?

In my code, I have a loop on rxDetails that is supposed to add a new field payAmount if any rxNumber matches with the data. However, when I run the forEach loop as shown below, it always misses the rxNumber 15131503 in the return. I'm not sure what I did wrong here. I noticed that the forEach loop is skipping one of the elements but I can't figure out why.

Here is the data:

const rxDetails = [
  {
    "drugName": "TRILIPIX 135MG CPDR",
    "rxNumber": "15131523",
    "lldIndicator": "N"
  },
  {
    "drugName": "GILENYA 0.5MG CAPS",
    "rxNumber": "15131519",
    "lldIndicator": "N"
  },
  {
    "drugName": "JAKAFI 5MG TABS",
    "rxNumber": "15131503",
    "lldIndicator": "Y"
  },
  {
    "drugName": "FENOFIBRATE MICRONIZED 134MG CAPS",
    "rxNumber": "15131510",
    "lldIndicator": "N"
  },
  {
    "drugName": "LIPITOR 10MG TABS",
    "rxNumber": "15131506",
    "lldIndicator": "N"
  },
  {
    "drugName": "KEFLEX 750MG CAPS",
    "rxNumber": "15131522",
    "lldIndicator": "N"
  }
]

const data = [{
        "drugName": "TRILIPIX 135MG CPDR",
        "rxNumber": "15131523",
        "lldIndicator": "N",
        "payAmount": "10"
    },
    {
        "drugName": "GILENYA 0.5MG CAPS",
        "rxNumber": "15131519",
        "lldIndicator": "N",
        "payAmount": "8"
    },
    {
        "drugName": "METFORMIN",
        "rxNumber": "15425789",
        "lldIndicator": "Y",
        "payAmount": "0.50"
    },
    {
        "drugName": "FENOFIBRATE MICRONIZED 134MG CAPS",
        "rxNumber": "15131510",
        "lldIndicator": "N",
        "payAmount": "2.56"
    },
    {
        "drugName": "LIPITOR 10MG TABS",
        "rxNumber": "15131506",
        "lldIndicator": "N",
        "payAmount": "7.76"
    },
    {
        "drugName": "KEFLEX 750MG CAPS",
        "rxNumber": "15131522",
        "lldIndicator": "N",
        "payAmount": "17.88"
    }
]

The issue seems to be in the main.ts file:

private getDrugsLastPrice(rxDetails: any, data: any) {
        let isDrugFound: boolean = false;
        const drugsArray: any = [];
        rxDetails.forEach((item: any) => {
            for (const element of data) {
                    if (item.rxNumber === element.rxNumber) {
                        isDrugFound = true;
                        const singleDrug = {
                            rxNumber: item.rxNumber,
                            lldIndicator: item.lldIndicator,
                            drugName: item.drugName,
                            payAmount: element.payAmount
                        };
                        drugsArray.push(singleDrug);
                    }

             }
            if (!isDrugFound) {
                drugsArray.push(item);
            }

        });

        return drugsArray;

    }

getDrugsLastPrice(rxDetails,data);

The expected output should be:

[{
        "drugName": "TRILIPIX 135MG CPDR",
        "rxNumber": "15131523",
        "lldIndicator": "N",
        "payAmount": "10"
    },
    {
        "drugName": "GILENYA 0.5MG CAPS",
        "rxNumber": "15131519",
        "lldIndicator": "N",
        "payAmount": "8"
    },
    {
        "drugName": "JAKAFI 5MG TABS",
        "rxNumber": "15131503",
        "lldIndicator": "Y"
    },
    {
        "drugName": "FENOFIBRATE MICRONIZED 134MG CAPS",
        "rxNumber": "15131510",
        "lldIndicator": "N",
        "payAmount": "2.56"
    },
    {
        "drugName": "LIPITOR 10MG TABS",
        "rxNumber": "15131506",
        "lldIndicator": "N",
        "payAmount": "7.76"
    },
    {
        "drugName": "KEFLEX 750MG CAPS",
        "rxNumber": "15131522",
        "lldIndicator": "N",
        "payAmount": "17.88"
    }
]

Answer №1

The primary issue at hand is the need to initialize the isDrugFound variable within the forEach loop. By keeping it set to true, it remains that way throughout and this causes the problem.

I've refactored your code to eliminate the need for the boolean variable altogether.

This solution utilizes Array#map, Array#find, spread syntax, and destructuring.

const rxDetails=[{"drugName":"TRILIPIX 135MG CPDR","rxNumber":"15131523","lldIndicator":"N"},{"drugName":"GILENYA 0.5MG CAPS","rxNumber":"15131519","lldIndicator":"N"},{"drugName":"JAKAFI 5MG TABS","rxNumber":"15131503","lldIndicator":"Y"},{"drugName":"FENOFIBRATE MICRONIZED 134MG CAPS","rxNumber":"15131510","lldIndicator":"N"},{"drugName":"LIPITOR 10MG TABS","rxNumber":"15131506","lldIndicator":"N"},{"drugName":"KEFLEX 750MG CAPS","rxNumber":"15131522","lldIndicator":"N"}]
const data=[{"drugName":"TRILIPIX 135MG CPDR","rxNumber":"15131523","lldIndicator":"N","payAmount":"10"},{"drugName":"GILENYA 0.5MG CAPS","rxNumber":"15131519","lldIndicator":"N","payAmount":"8"},{"drugName":"METFORMIN","rxNumber":"15425789","lldIndicator":"Y","payAmount":"0.50"},{"drugName":"FENOFIBRATE MICRONIZED 134MG CAPS","rxNumber":"15131510","lldIndicator":"N","payAmount":"2.56"},{"drugName":"LIPITOR 10MG TABS","rxNumber":"15131506","lldIndicator":"N","payAmount":"7.76"},{"drugName":"KEFLEX 750MG CAPS","rxNumber":"15131522","lldIndicator":"N","payAmount":"17.88"}]

const res = rxDetails.map(item=>{
  const d = data.find(({rxNumber})=>rxNumber===item.rxNumber);
  return d ? {...item, payAmount: d.payAmount} : {...item};
});

console.log("Number of elements: " + res.length);
console.log("Number with payAmount prop: " + res.filter(o=>o.payAmount !== undefined).length);
console.log("Number without payAmount prop:" + res.filter(o=>o.payAmount === undefined).length);
console.log(res);

Answer №2

The variable isDrugFound is not being reset within your forEach loop. This means that once a match is found, the next iteration will still have isDrugFound set to true. As a result, only elements that are in the data array will be pushed to the final output. If a match is found, all subsequent elements must also be present in the data array to be included.

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

ffmpeg is successfully converting less than half of my images into a video

Utilizing ffmpeg to convert a series of images into a timelapse video has been seamless when executed through the command line. ffmpeg -r 3 -i /var/folders/qj/n910kwdj4gvbmy_z2ffc5lcc0000gp/T/tmp-22129yvIsrbso4TEu/image%03d.jpg -s hd1080 -vcodec libx264 t ...

Utilize time in submitting a form

Is it possible to schedule a form submission at a specific time, such as 12:00? I have already created a countdown timer and now would like the form to be submitted automatically at a certain time. <html> <head> </head> <body> ...

Working with node.js to set up an ordering function

I am working with node.js and express3. To use mongodb, I decided to install the mongo-lazy package. This is the simple GET router I have set up: var db = require('mongo-lazy').open({ db: 'somedb', host: '127.0.0.1' ...

Switching back and forth between classes prevents the animation from playing continuously, causing it to jump straight to the end

Currently, I am in the process of animating a hamburger menu with a unique twist. The idea is to have the top and bottom lines smoothly translate to the middle and then elegantly rotate into an X shape when clicked. My approach involves toggling between tw ...

What action is initiated when the save button is clicked in ckEditor?

Incorporating a ckeditor editor into my asp.net application has been successful. At this point, I am looking to identify the event that is fired by ckeditor when the save button in the toolbar is clicked. Has anyone come across this information? ...

Enhancing JavaScript with TypeScript: implementing functional mixins

I'm in the process of creating functional mixins using TypeScript. Below is the code I have written so far: const flying = (o: object) => { let isFlying = false; return Object.assign({}, o, { fly() { isFlying = true; return thi ...

Leveraging animations in Angular2 that are defined outside of a component

I've recently put together a basic component @Component({ selector: 'saved-overlay', templateUrl: './saved-overlay.html', exportAs: 'saved-overlay', animations: [ trigger('inOut', [ transition ...

Error in function due to index exceeding range

I'm trying to create a function that takes two arrays of integers as parameters - Numbers and Numbers1. The goal is to multiply each element in Numbers at index "i" with the corresponding element in Numbers2, then calculate the total sum of these mult ...

The Joi validate() function will return a Promise instead of a value when used within an asynchronous function

Trying to understand how async functions and the Joi.validate() function behave. Below is a function used for validating user input. const Joi = require("joi"); const inputJoiSchema= Joi.object().keys({ name: Joi.string(), email: Joi.string().require ...

What is the best way to allocate a unique color to every item within an array?

I've been working on some JavaScript code that pulls a random color from a selection: const colors = [blue[800], green[500], orange[500], purple[800], red[800]]; const color = colors[Math.floor(Math.random() * colors.length)]; Within my JSX code, I ...

What are the best practices for properly formatting a function that returns a JSON string?

Recently, I embarked on a project utilizing the CityBikes API to access real-time data from bike-sharing stations in cities worldwide (). Initially, I gathered various links to obtain the necessary data and then developed a function called extractStationDa ...

Guide for invoking a servlet via a navigation bar hyperlink and implementing a jQuery feature for smooth scrolling upon clicking

Is there a way to call a servlet from a navigation bar href link and at the same time trigger a jQuery function for smooth scrolling down? I attempted to call the servlet using an onclick href link, it successfully calls the servlet but does not trigger t ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

Node.js, PHP, and the Express framework

I have a project where I need to develop a to-do list and a form that allows users to upload png files using Node.js. Currently, I am using the following packages: { "name": "todo", "version": "0.0.1", "private": true, "dependencies": { "ejs": ...

Exploring AngularJS unit testing: integrating async and await with Jasmine

I'm currently facing a challenge with unit testing my Angular service using the async/await keywords in the respective (Jasmine) unit tests below. The test for the built-in Promise is functioning correctly, however, I am encountering difficulties in g ...

Having trouble with Ionic 4 navigation not triggering after a single click, requiring multiple clicks to navigate

I have a long list of items, around 40 in total, that load a page describing each item with photos, URLs, and other content. However, I find that I need to click two to three times before reaching this page. I suspect that the excessive use of HTML compone ...

Problem with Layering in Javascript Canvas Game using Kinetic JS

Currently, I am attempting to replicate the game found at and delving into html5 canvas and kineticJS for my study. Here is the link to my fiddle: http://jsfiddle.net/2WRwY/7/ The issues I am facing are as follows: The tail part of the player in the f ...

Modify the layout of the date selector to display weekdays instead - material ui

How can I change the datepicker format to display weekdays (Monday, Tuesday,..) instead of MM/dd/yyyy? Currently, the datepicker is set up with the format format="MM/dd/yyyy". Would it be possible to modify this? Here is the source code: <MuiPickers ...

What is the best way to successfully send an object through AJAX once all its updates are completed?

I am experiencing an issue with my JavaScript code within an event: var userData = tableWidget.grid('userData'); console.log(tableWidget.grid('userData')); $.ajax({ "url": "../../server/query.aspx?tableEvent=reordercolumns&tabl ...

Navigating API data conversion on the frontend using Object-Oriented Programming

Currently, I am facing a challenge while developing the frontend of a web application using TypeScript. The dilemma revolves around efficiently converting a data object from an API response into a format suitable for the application. Let's consider r ...