Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda