Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda