Merging two arrays in Typescript and incrementing the quantity if they share the same identifier

I am currently working on my Angular 8 project and I am facing a challenge with merging two arrays into one while also increasing the quantity if they share the same value in the object. Despite several attempts, I have not been able to achieve the desired result.

mergedOrderList: any[]= [];

lstOldOrder: any[] = [
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},];

lstNewOrder: any[] = [
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},
{id: "", products_id: "", qty: 1, ...},];

lstNewOrder.forEach(newOrder => {

    let isDubplicated: boolean = false;

    lstOldOrder.forEach(oldOrder => {

      if (newOrder.products_id == oldOrder.products_id) {
        oldOrder.qty += newOrder.qty;
        isDubplicated = true;
        mergedOrderList.push(oldOrder);
      }
    });

    if (!isDubplicated) {
      mergedOrderList.push(newOrder)
    }

  });

Although this method works when both orders have the same products_id, it encounters an issue when the new order lacks a products_id. In such cases, the old order gets skipped and only the new order is added to the list. I am uncertain whether I have implemented this correctly. Your assistance is greatly appreciated. Thank you.

Answer №1

It seems like the issue lies in how you are merging data from lstOldOrder into mergedOrderList only if the product_id of a new list item matches with any item in the old list.

As a result, if all items in lstNewOrder are new, you won't see any items from the old list.

A more effective approach would be:

Add the item to the mergedOrderList, but increase the quantity if a match is found.

mergedOrderList = [];

lstOldOrder = [
  { id: "1", products_id: "", qty: 1 },
  { id: "2", products_id: "", qty: 1 },
  { id: "3", products_id: "", qty: 1 },
];

lstNewOrder = [
  { id: "4", products_id: "", qty: 1 },
  { id: "5", products_id: "", qty: 1 },
  { id: "1", products_id: "", qty: 1 },
];

lstNewOrder.forEach((newOrder) => {
  Oindex = -1;
  lstOldOrder.forEach((item, index) => {
    if (item.id == newOrder.id) {
      Oindex = index; // Find the index of the item in the old array
    }
  });

  if (Oindex != -1) { // If the item was found in the old array
    newOrder.qty += lstOldOrder[Oindex].qty; // Update the quantity in the new order item
    lstOldOrder.splice(Oindex, 1); // Remove the item from the old array
  }
  mergedOrderList.push(newOrder); // Add the item to the merged list
});

mergedOrderList.concat(lstOldOrder); // Finally, add any remaining items from the old list

Apologies for not handling all edge cases properly in the code. Please feel free to make any necessary edits to this solution for the benefit of others.

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

The variable 'user' is being accessed before being properly initialized - in Angular

I've been doing some research on Google and StackOverflow to try and troubleshoot this error, but I'm still having trouble getting it fixed. Can anyone provide assistance? Below is the content of my auth-service.ts file: import { Injectable } fr ...

The assignment of Type Program[] to a string[] is not valid

I am working with a class that contains information about different programs. My goal is to filter out the active and inactive programs, and then retrieve the names of those programs as an array of strings. Below is the structure of the Program class: ex ...

The Nestjs ClientMqtt now has the capability to publish both pattern and data to the broker, as opposed to just sending

I am currently utilizing Nestjs for sending data to a Mqtt Broker. However, I am facing an issue where it sends both the pattern and data instead of just the data in this format: { "pattern": "test/test", "data": " ...

Angular Material UI: Nested Table Component

I am dealing with a table that has four static headers and two static columns. The data in the last two columns changes based on certain conditions. I need to convert this table into an Angular Material table. The first table is a standard HTML table. Th ...

What could be the root of this next.js build issue occurring on the Vercel platform?

I recently upgraded my next.js project to version 12.0.7, along with Typescript (4.5.4) and pdfjs-dist (2.11.228), among other libraries. Locally, everything runs smoothly with the commands yarn dev for development and yarn build for building. However, af ...

The Sequence of Import Statements in Angular 2

The Angular Style Guide provides recommendations on Import line spacing: It is suggested to include one empty line between third-party imports and application imports. Consider arranging import lines in alphabetical order based on the module. For destruc ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

Setting up a React state with an Object using Typescript: A step-by-step guide

As someone who is new to TypeScript, I have a solid understanding of how to set up an interface for certain types. However, I am struggling to comprehend how the same concept would apply to an Object type. interface MyProps { defaultgreeting: 'He ...

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

Utilizing a personalized directive within a ionic popup

I am currently using the ion-textarea autosize directive: import { Directive, HostListener, ElementRef } from '@angular/core'; @Directive({ selector: 'ion-textarea[autosize]' }) export class AutoResizeTextareaDirective { readonly ...

Is it possible to add new values to a GraphQL query?

I am currently utilizing GraphQL and Typeorm in conjunction with an Oracle Database, specifically focusing on retrieving all data from a specific table. The query that is being executed is: SELECT "inventory"."id" AS "inventory_id", "inventory"."value" AS ...

Issue with Datatables not loading on page reload within an Angular 7 application

Incorporating jQuery.dataTables into my Angular 7 project was a success. I installed all the necessary node modules, configured them accordingly, and added the required files to the angular.json file. Everything functioned perfectly after the initial launc ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

When using npm link, it searches for the module in the src directory rather than the dist directory

In my experience with Angular CLI Builder, I have implemented a custom builder to extend the asset configuration in angular.json for libraries that have their own assets. To manage my workspace, I utilized nrwl. I created an Angular CLI builder library an ...

Should one prioritize learning TypeScript over diving into Angular2?

Should I prioritize learning TypeScript before diving into AngularJS 2? ...

How to conditionally import various modules in Next.js based on the environment

Having two modules 'web,ts' and 'node.ts' that share similar interfaces can be challenging. The former is designed to operate on the client side and edge environment, while the latter depends on node:crypto. To simplify this setup, I a ...

Create boilerplate code easily in VS Code by using its feature that generates code automatically when creating a

Is there a way to set up VS Code so that it automatically creates Typescript/React boilerplate code when I create a new component? import * as React from "react"; export interface props {} export const MyComponent: React.FC<props> = (): J ...

Learn how to generate specific error messages based on the field that caused the failure of the @Column({ unique: true }) Decorator. Error code 23505

Hey there! I'm currently facing an issue while trying to handle Sign Up exceptions in my code. I want to inform the user if their username OR email is already in use. Although using the decorator @Column({ unique: true}) allows me to catch error 23505 ...

Guidelines on sorting an array of strings by the presence of elements from another array of strings

Issue Resolved: Trouble Selecting Own Answer An issue arose when I tried to select my own answer for a problem I encountered. The problem involved loading an array from JSON into an NSMutableArray. Within this array, the entry "AllowedTo" contained a valu ...

The parameters provided in TypeScript do not align with any signature of the call target

In JavaScript, a function can be called with any number of parameters. If a parameter is not passed, it will default to undefined without causing an error. Below is a code snippet for reference: function test(a,b){ if(b){console.log(b)} else{console ...