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.