Tips for manipulating 2 arrays where the value in one array is reliant on the value in another array

Currently, I have two arrays - arrayGuest and arrayRent. They both contain objects with a common field, GuestID. My goal is to create a list that combines fields from both arrays when their guestIDs match.

The structure of the objects is as follows:

class Guest {
    guestID: number;
    firstName: string;
    lastName: string;
    panCardNumber: string;
    address: string;
    city: string;
    state: string;
    typeOfRoom: string;
}

class Rent {
    guestID:number;
    amount:number;
    dateOfPayment: Date;
}

Below are the samples of the two arrays involved:

let arrayGuests: Array<Guest> = [
    {guestID:1,firstName:"Jay",lastName:"Shetty",panCardNumber:"FSDDE2235A",address:"150ft Ring Road",city:"Rajkot",state:"Gujarat", typeOfRoom: roomType.AC},
    // other entries omitted for brevity...
]

let rentArray : Array<Rent>= [
    {guestID:1,amount:5000,dateOfPayment:new Date("2022-03-01")},
    // other entries omitted for brevity...
]

The desired result format would be similar to: GuestID:1, Name : xyz, amount = 5000

Answer №1

Given that both arrays are sorted, we can merge them based on the index value.

interface User {
    userID: number;
    username: string;
    email: string;
}

interface Order {
    orderID: number;
    amount: number;
    date: Date;
}

type Combined = User & Order;

const userArray: Array<User> = [
    {
        userID: 1,
        username: 'JohnDoe',
        email: 'john.doe@example.com',
    },
    {
        userID: 2,
        username: 'JaneSmith',
        email: 'jane.smith@example.com',
    }
];

const orderArray: Array<Order> = [
    { orderID: 1, amount: 100, date: new Date('2022-03-01') },
    { orderID: 2, amount: 150, date: new Date('2022-03-02') },
];

// Merge function to combine user and order data
const mergeArrays = (users: User[], orders: Order[]): Combined[] => {
    return users.map((user, i) => {
        return {
            ...user,
            ...orders[i],
        };
    });
};

console.log(mergeArrays(userArray, orderArray));

Compiled:

"use strict";
const userArray = [
    {
        userID: 1,
        username: 'JohnDoe',
        email: 'john.doe@example.com',
    },
    {
        userID: 2,
        username: 'JaneSmith',
        email: 'jane.smith@example.com',
    }
];
const orderArray = [
    { orderID: 1, amount: 100, date: new Date('2022-03-01') },
    { orderID: 2, amount: 150, date: new Date('2022-03-02') },
];
const mergeArrays = (users, orders) => {
    return users.map((user, i) => {
        return Object.assign(Object.assign({}, user), orders[i]);
    });
};
console.log(mergeArrays(userArray, orderArray));

Explore the Array.prototype.map() method

Discover more about the Spread Operator

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

Tips for setting up a bookmark in bootstrapvue

Hello everyone, I am currently working with bootstrapvue and I need help figuring out how to add a favorite icon. The documentation only provides icons for rating systems. I have a list of reports and I want users to be able to mark their favorites, simil ...

Fetching the name of a JSON object in JavaScript converted to a string

Is there a way to retrieve the name 'muxEnvironments' as a string from the object? I need it in order to analyze and compare the content type. When I use console.log(obj), the entire object is displayed. My objective is something like this: jso ...

Querying a collection in Mongoose for an array of ObjectIds

I've been struggling with this for a few hours now, so I thought I'd post here for help. My issue involves using the find() operator in Mongoose to determine if a key matches any single element in an array. It's similar to the question asked ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

Exploring Methods to Access External Iframes Using PHP or JavaScript

I need assistance tracking my package that was sent through the local post service. The tracking information can be found at this link: . Using the tracking number RF166699170SK, I should be able to locate the package. However, when I attempt to retrieve ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

What is the best method for implementing page transitions between components in NextJS?

My goal is to create a form that smoothly slides to the right, similar to the one seen on DigitalOcean's website when you click "Sign up using email" here: . While the transition itself is relatively simple, I noticed that DigitalOcean uses 2 separat ...

How is it that my initial response appears correct in the first log, but then suddenly changes to a 1?

I've encountered a strange issue where the response appears correctly in the initial log, but later changes to a '1' when console.log(data); is called. The screenshot illustrates the pattern: https://i.sstatic.net/zaXcg.png If you expand ...

Is there a solution to resolving the type error that I am unable to identify?

I am attempting to implement a custom cursor feature in Vue 3, but unfortunately my code is not functioning as expected. Below you can find the code snippet I have been working on: <template> <div id="cursor" :style="cursorPoi ...

Mastering the art of iterating through a JSON response

Looking to populate a combobox with data from the database. Upon accessing mystream.php?theLocation=NewYork, I receive the following JSON response: RESULT {"result": [{"theID":"36"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork ...

What is the best way to position a semi-circular donut graph in the center?

I am attempting to showcase a doughnut or semi-circle chart within a materialize card, which is a responsive div element. My goal is to present simple data and utilize the chart as a progress bar. I took inspiration from the example provided in the HighCh ...

Tips for modifying only one property after receiving an object from an HTTP GET request

Within my Angular application, I have defined an object structure like this: export class Article { id: number; author: number; title: string; content: string; date: Moment; readingTime: number; draft: boolean; constructor(obj: Partial< ...

Tips for developing a sophisticated HTML quiz

I have spent countless hours perfecting this quiz. I have successfully created a quiz that reveals solutions at the end, but I want to take it one step further. I envision the answers appearing after each incorrect response from the user, and no answer sho ...

How to locate the index.js file within my application using Node.js?

Directory Structure bin - main.js lib - javascript files... models - javascript files... node_modules - folders and files public - index.html route - javascript files... index.js package.json I am using Express and angular.js. The ser ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

Ensuring that the text in the Bootstrap navbar is responsive for all screen

Yesterday, I inquired about how to modify my navbar menu to switch from horizontal to vertically arranged depending on layout. However, I've noticed that the responsiveness is not consistent when adjusting the window size. Is there a way to ensure my ...

Bootstrap 4 modal experiencing issues with the form end tag functionality

Currently, I am facing an issue while attempting to incorporate a confirmation delete feature using a Bootstrap 4 modal in my Laravel project. The problem arises when the modal is opened, and the submit button fails to function. Upon inspecting the browser ...

Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...