Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
Combining an array of objects with some conditions

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Thats basically what you need to do. But it doesn't seem that messy or complicated to me.

function combine(a: FareZone[], b: FareZone[]) : FareZone[] {
    const res = [...a]
    b.forEach(zone => {
      const aZone = res.find(x=> x.name == zone.name);
      if (!aZone) {
        res.push(zone);
      } else {
        zone.stops.forEach(stop => {if (!aZone.stops.some(s => s.code == stop.code)) { aZone.stops.push(stop); }}) 
      }
    })
    return res;
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!