I have the following code:
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'}] }];
I would like to end up with the following combined list:
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 Logic
The new combined list should have all possible zones once (the name on FareZone
is unique). When a zone exists in both lists (the inbound and the outbound), their stops should be combined and be unique.
What is an elegant way I can achieve this in JavaScript/TypeScript? Here is a CodePen.
PS. I was able to do this, but it took many lines of code and it was messy.
I basically looped through the first list, and found the items that did not exist in the other, and then did the same with the second list, then combined the stops on each list.
UPDATE: I do not think my question is a duplicate of this one. That one is about removing duplicates in a single array, this one is about combining two arrays of complex objects with some logic.