Combining Arrays Together in TypeScript

I am in need of a solution to merge two arrays into one using TypeScript.

First Array Object:

export interface Item{
        Label : string,
        Code : string,
        Price : number,
    }
    

Second Array Object:

export interface Amount
    {
         Code :  string,
         Amount: number
    }
    

Result Array Object:

export interface CombinedList{
        Code : string,
        ItemAmount : number,
        ItemPrice : number
    }
    

In the resulting array, I aim to combine the Item and Amount arrays based on their shared Code values. (Each Code has 3 matching elements in Item and Amount arrays).

Example:

ItemsArray : Item[] = 
    [{ Label : "One", Code : "ONE", Price : 5,86}, 
    {Label : "Two", Code : "TWO", Price : 9,99}, 
    {Label : "Three", Code : "THR", Price : 752}]
    
    AmountsArray : Amount[] = 
    [{ Code : "ONE", Amount : 120}, 
    {Code :"TWO", Amount : 250}, 
    {Code :"THR", Amount : 165}]
    

And the desired result is:

CombinedArray : CombinedList[] = 
    [{Code : "ONE", ItemAmount : 120, ItemPrice: 5,86 }, 
    {Code :"TWO", ItemAmount : 250, ItemPrice: 9,99}, 
    {Code :"THR", ItemAmount : 165, ItemPrice: 752}]
    

Answer №1

Here is my approach:

To start, I would first convert the amounts into a key-value pair format, where the code serves as the key and the amount serves as the value. This allows for easy retrieval of amounts based on their corresponding codes:

const amountsByKey = AmountsArray.reduce((byCode, amount) => { byCode[amount.Code] = amount; return byCode; }, {} as { [key: string]: Amount });

The next step involves mapping the items in order to add any missing fields:

const CombinedArray = ItemsArray.map(item => ({ Code: item.Code, ItemAmount: amountsByKey[item.Code].Amount, ItemPrice: item.Price }));

If the arrays maintain a consistent order (based on codes), it is possible to directly combine them using a zip operation:

const CombinedArray = ItemsArray.map((item, index) => ({ Code: item.Code, ItemAmount: amounts[index].Amount, ItemPrice: item.Price }));

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

Struggling to access the 'payload' property of an undefined object? In TypeScript, you can easily bind and access JSON objects using *ngFor directive

I've been attempting to retrieve highscores from the server using node angular and making an http request. Although I successfully obtain the JSON file from the server, I am encountering difficulty accessing the fields for processing in the *ngFor lo ...

How can we limit the generic type T in TypeScript to ensure it is not undefined?

I have created a function called get(o, key), which is designed to work with any Object that meets the criteria of the { get: (key: K) => R } interface. Furthermore, I am interested in restricting the result variable R to not allow it to be undefined. ...

Make the if statement easier - Angular

Would you like to know a more efficient way to streamline this If statement? The variables are all strings and are reused in both conditions, but the outcome varies depending on whether it returns true or false. if(params.province && !params.str ...

Guide for launching Electron on a local host server during development and for production builds

I have a project using Next.js + Electron + Typescript. I used the npx create-next-app --example with-electron-typescript command to generate the initial code. When I run npm run dev (which actually runs npm run build-electron && electron . ), the ...

Using the return statement to set a value from a callback function in TypeScript

As I retrieve data from an array of class People, each person has an attendance list represented by Observable<any[]>. // Defining the Person class class Person { id: number; name: string; attendance: Observable<any[]>; // Represents ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

Steps to troubleshoot a simple function that manages asynchronous tasks

Looking to develop a versatile function that can handle async functions, execute them, and catch any errors that may arise. Coming from a javascript background, I initially managed to create a function that did just this. However, my attempt to enhance it ...

Tips for Using Typescript Instance Fields to Prevent Undefined Values

After creating a few Typescript classes, I encountered an issue where I would get an undefined error when trying to use them after instantiating. I experimented with initializing my fields in the constructor, which resolved the problem, but I don't t ...

Testing chai: verifying the inclusion of object types in an array

I am currently in the process of testing a Node.js/Typescript application. My goal is to have my function return an array consisting of objects. These objects should adhere to the following type: type myType = { title: string; description: string; ...

Angular6 returns the result after subscribing to an HTTP POST request

Currently, I am in the process of learning angular and attempting to create a component that allows users to register through my web API. Within my component, the code on form submission looks like this: onSubmit(contactFormRef: NgForm) { const resu ...

Navigating the process of transferring a function to a functional component within React

Hey there, I'm fairly new to using React and TypeScript and I am facing a small issue with moving a function from the file App.tsx to a functional component called WordAddingForm.tsx. Any help would be greatly appreciated! Let's start with my Ap ...

Save Component Characteristics in a type-safe array

Is it possible in Svelte to define a strongly typed array that matches the properties exported by a specific component? For instance, if I have the following code snippet, const things = [], is there a way for Svelte to recognize that each item within the ...

In order to resolve the issue in nextjs 13 where the argument is of type 'any[] | null' and cannot be assigned to the parameter of type 'SetStateAction<never[]>', a potential solution may involve explicitly checking for null values

My current project uses Next.js 13 and is based on the Supabase database. I am attempting to fetch data from Supabase and assign it to a variable using useState, but encountering the following error: Argument of type 'any[] | null' is not assigna ...

Packaging an NPM module to enable unique import paths for Vite and Typescript integration

Is there a way to package my NPM module so that I can use different import paths for various components within the package? I have looked into webpack solutions, but I am working with Vite and TypeScript. This is the structure of my package: - src - ato ...

Show the outcome stored within the const statement in TypeScript

I am trying to display the outcome of this.contract.mint(amount, {value: this.state.tokenPrice.mul(amount)}) after awaiting it. I want to see the result. async mintTokens(amount: number): Promise<void> { try { let showRes = await this.c ...

Transfer the unique field name to a universal assistant

Consider the code snippet provided in this playground: class A { private z = 0 } type K = "z" type ValidKeys = A[K] extends any ? K : never The type ValidKeys compiles correctly and matches K only when K represents a subset of keys from A. It ...

Angular: Tailoring the Context Menu

Currently, I am utilizing a helpful tutorial to implement a custom context menu feature. The main issue I am facing is that when a user interacts with the list items, I want the correct index of each item to be displayed. However, at the moment, clicking o ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

MQTT: The method net.createConnection does not exist

Following the guide at https://www.npmjs.com/package/mqtt#install to establish an mqtt connection, I encountered a render error indicating _$$_REQUIRE_(dependencyMap[1], "net").createConnection(port, host)','_$$_REQUIRE(_dependencyMap[ ...

Combine arrays using union or intersection to generate a new array

Seeking a solution in Angular 7 for a problem involving the creation of a function that operates on two arrays of objects. The goal is to generate a third array based on the first and second arrays. The structure of the third array closely resembles the f ...