Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet:

interface Stop {
  code: string 
}

interface FareZone {
    name: string;
    stops: Stop[];
}

const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B', stops: [{ code: 'C01'}, { code: 'C02'}] }];
const inbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}, { code: 'C04'}] }, {name: 'Zone C', stops: [{ code: 'C08'}] }];

In order to create a combined list, here is my desired output:

const combined: FareZone[] = [
{name: 'Zone A', stops: [{ code: 'C00'}, { code: 'C04'}] },
{name: 'Zone B', stops: [{ code: 'C01'}, { code: 'C02'}] },
{name: 'Zone C', stops: [{ code: 'C08'}] }
];

The Approach

To achieve this in JavaScript or TypeScript, I am seeking an elegant solution. The new combined list should include all unique zones (uniqueness based on the name in FareZone). If a zone exists in both the inbound and outbound lists, their stops should be merged and remain unique.

If you wish to see my initial attempt, it can be viewed in this CodePen link.

PS: While I managed to accomplish this task previously, the implementation was lengthy and cluttered. My method involved iterating through each list separately, identifying items exclusive to one list, and then merging the stops accordingly.

UPDATE: I do not believe my query duplicates another post found at this location. The mentioned question pertains to removing duplicates within a single array, whereas mine involves combining two arrays of complex objects with distinct logic.

Answer №1

That's pretty much the gist of it. It doesn't strike me as overly messy or complex.

function mergeZones(zoneA: FareZone[], zoneB: FareZone[]) : FareZone[] {
    const result = [...zoneA]
    zoneB.forEach(newZone => {
      const existingZone = result.find(x=> x.name == newZone.name);
      if (!existingZone) {
        result.push(newZone);
      } else {
        newZone.stops.forEach(stop => {if (!existingZone.stops.some(s => s.code == stop.code)) { existingZone.stops.push(stop); }}) 
      }
    })
    return result;
}

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

What is the purpose of the "Dot" symbol in the "runtimeArgs" property of the launch.json file in Visual Studio Code?

As I opened my Visual Studio Code today, a notification greeted me about a new update. Without hesitation, I went ahead and installed it, assuming it would be like any other update I've had in the past. However, after updating to version 1.22.1, I enc ...

Learn how to gradually make text disappear and reappear using JavaScript or jQuery

I am a beginner in JavaScript and jQuery, and I am trying to achieve a text fade-out effect. Once the text has completely faded out, I want it to return with the same fade-in effect. I have been exploring if statements and fadeIn effects, but I am strugg ...

Introducing NextAuth: Empowering multiple users to access a single account

I've been pondering if it's possible to have multiple users for a single account provider. One idea is to create a session with a specific field indicating the active user (the one currently logged in) and then allow for easy switching between us ...

Passing an array of ID's between two components in Angular: A comprehensive guide

Greetings fellow readers, I have encountered a new challenge in my Angular project. I need to pass an array of IDs from one component to a completely unrelated component. Most solutions suggest using ViewChild, Input, or Output, but since the components ar ...

How can I eliminate the empty spaces around a bar chart in Kendo UI?

Struggling to eliminate the extra space surrounding the Kendo UI chart below. Could this be due to a gap or spacing issue? The goal is to create a single-line bar chart with only grey appearing on the right side. Access JSFiddle Codes Here $(doc ...

Is it possible to observe cross-domain Javascript requests in Firebug or any alternative browser extension?

Is there a way to monitor cross-domain JavaScript requests made on a webpage? Is it possible with Firebug or any other plugin? Consider this scenario: If I visit stackoverflow.com and they incorporate an external JavaScript file (such as Google Analytics) ...

Navigate down to the bottom of the element located on the webpage

I'm trying to create a feature where clicking an anchor tag will smoothly scroll to a specific element on the page. Currently, I am using jquery scrollTo for this purpose. Here's the code snippet: $.scrollTo( this.hash, 1500, { easing:&apos ...

Optimal approach to displaying views with Express.js and EJS

Recently, I came across a website that only renders EJS templates using Express.js routing. All the routes are defined in the /routes/index.js file. As the file grows with more routes being added, I am thinking about restructuring it to make it more develo ...

Unspecified error encountered in the VUE selection view

I am facing an issue with the undefined value in the select view while attempting to add a new project. Could you suggest a solution? I tried using v-if but it didn't work for me. This is how my code looks: <v-select v-model="pro ...

Switch the appearance between two elements

In my HTML table, I have different levels of content - from main "contents" to nested "sub-contents" and even deeper "sub-sub-content". My goal is to hide all sub-content within the content cell that I click on. <table> <tr class=' ...

The dimensions of the box are not predetermined by the size of the photo

I'm attempting to develop a photo gallery that emulates the style of (using the Unsplash API -> ) However, the size of the container box does not adjust properly with the photos. <div className="imageGrid__container"> <di ...

Handling MySQL insertIds and errors in Node.js using MySQL is a crucial aspect of

I am struggling to handle errors and retrieve the insertId after creating a new row in my database using code from the official page of mysqljs/mysql. How can I modify my code to achieve this? var post = {deviceImei: deviceInformation.deviceImei, created_ ...

Using jQuery and regex to validate a long string containing lowercase letters, uppercase letters, numbers, special characters, and

Good day, I've been struggling with jquery regex and could really use some assistance. I've been stuck on this since last night and finally decided to seek help :) Here is my regex code along with the string stored in the 'exg' variabl ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

Unable to get ng-submit function to work properly within the Laravel PHP framework

Hello everyone, I have an inquiry regarding Laravel/AngularJS. In my project, there is a form where users can post questions. However, when I click the submit button, no requests are sent (as per inspection in Google Chrome). Interestingly, the Log in int ...

What's preventing the mobx @computed value from being used?

Issue: The computed value is not updating accordingly when the observable it is referencing goes through a change. import {observable,computed,action} from 'mobx'; export default class anObject { // THESE WRITTEN CHARACTERISTICS ARE COMPUL ...

JavaScript scroll event not firing

I have searched multiple questions on SO to avoid duplication, but none of the solutions worked for me. My goal is to toggle the visibility of a button based on scroll position. I tried creating a scroll event listener to trigger a function that checks th ...

Obtain the distinct highest value for every vertical axis on a bar graph

I'm facing an issue with my code where I am appending multiple SVG elements and generating 3 different charts. The problem is that the maximum value evaluated from the y.domain() for each y-axis is taken as the maximum value from all of my data. Is t ...

What is the best way to access the second item using getByRole in React Testing Library when there is no specific name?

I am familiar with using the name option to select the first item here, but how can I go about selecting the second item if it does not have a name identified? -------------------------------------------------- button: Enter "Go": ...