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

Utilizing a function as a prop with varying parameter types in React using Typescript

I am encountering an issue while attempting to pass a function that updates state in React. VSCode is prompting me with a typing problem. The error message states Type '(value: string) => void' is not assignable to type '(value: string | ...

"Utilizing TypeScript with React: Creating a window onClick event type

My linter is not happy with the any type for window.onClick. What should be the correct type? import React, { useContext, useState } from 'react'; import { Link } from 'react-router-dom'; import { Global } from '../globalState&apo ...

Changing a group of objects in java

Requirement - I am presenting a list of objects below: [ TestObj{levelCode='123', operId='ABC', hrchyInd='S'}, TestObj{levelCode='456', operId='DEF', hrchyInd='S'}, TestObj{levelCode='123&ap ...

Mastering the Art of Injecting Objects from the Server

Utilizing Angular Universal, I am serving my Angular application through an Express server. The objective is to embed an environment object (from the server) into my application. To achieve this, I have created an InjectionToken export const ENVIRONMENT ...

Retrieving a global variable within a nested function

I am encountering a scope issue with my nested function while trying to pass two global variables. I need some help as I keep getting this error when running the code: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'use ...

I am facing a problem with the code for my React login page and router

My form page is built in react and typescript, utilizing JWT tokens on the API side. While there are no issues with the container page, I encountered an error on the index.tsx page where the routers are defined: A TypeScript error occurred in C:/Users/yusu ...

Ways to resolve issues related to null type checking in TypeScript

I am encountering an issue with a property that can be null in my code. Even though I check for the value not being null and being an array before adding a new value to it, the type checker still considers the value as potentially null. Can anyone shed lig ...

Property element does not exist in this basic TypeScript project

I'm diving into my initial TypeScript project and encountering an issue with the "style". I attempted to utilize style!, create an if(changeBackgroundColor){}, but without success. let changeBackgroundColor = document.querySelectorAll('[data-styl ...

Can a standard tuple be matched with its corresponding key?

This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red": type Fruits = { banana: 'yellow' | 'green' strawberry: 'red' } const fruit = <K extends keyof Fruits>(modu ...

Displaying subsets of data based on the identifier of the primary array

In my JSON file, I have an array containing various categories and their respective subcategories. { "Women": [ { "id" : 1, "name" : "See All", &q ...

What is the best way to combine a specific number of arrays in JavaScript?

Currently, I am working on a program that is designed to read lines from multiple text files and store those lines in separate arrays for each file. Eventually, the goal is to combine all of these arrays and randomly select an item from the merged array. H ...

Is it possible to declare language features in Typescript? For example, changing `!variable` to `no variable`

Can Typescript language features be declared within the app's source code? I want to enhance code clarity by implementing a small feature. Modified Null Test if (no userDetails) { // handle null } This new null test syntax is a little more conc ...

In my Angular 6 project, I am faced with the challenge of having two separate navbars and routes that need to be integrated into the same page

I have two different navigation bars that I need to configure. The first one is the primary navbar, while the second one is for a specific section of the project. I also need to ensure that the second navbar remains visible when a link in the footer is cli ...

Discrepancies in ESLint outcomes during React app development

As a newcomer to React development, I am encountering discrepancies between the errors and warnings identified in my project's development environment versus its production environment. Strangely, I have not configured any differences between these en ...

Having trouble getting url-loader to function properly with a customized webpack configuration in an Angular 8

I am currently implementing custom webpack to integrate webpack with Angular 8. My goal is to use url-loader to inline SVGs, as the server where the app will be deployed does not support the SVG image/svg+xml mimetype (and unfortunately, I cannot change th ...

What is the proper way to type the SubmitEvent so that the event.target.children property can be accessed

Below is the form I currently have: <form id="search" method="post"> <input type="text" name="query" id="search-field"/> </form> I am looking to add a submit event listener in TypeScript: ...

Extracting lines of varying lengths from a document

My goal is to create a loop that iterates line by line, extracting the digits at the start of each line into an integer array, and the characters into a 2D character array. I had initially considered using loops like, while (fscanf(file, "%d %c %c %c", &n ...

Why the CoreModule in Angular is a must-have for practical development

Though I have gained ample experience in developing Angular-UIs, there is one concept that continues to elude me - the true value of incorporating a CoreModule. To clarify, I understand the purpose of a SharedModule; it houses reusable components (such as ...

At times, MomentJS may miscalculate and add an incorrect number of hours

My goal is to add a specific amount of hours to a 24-hour time, but I'm encountering an issue with the time 00:00. The code I've written works correctly for all times except midnight. For example, if I have 01:30 and add 1 hour, it gives me 02:3 ...

Utilizing Directives to Embed Attributes

My current challenge involves changing the fill color of attributes in an in-line SVG using Angular and TypeScript. The goal is to have the SVG elements with a "TA" attribute change their fill color based on a user-selected color from a dropdown menu. Howe ...