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

117
Visualizações
Replace the array of elements using another array of elements if its have both common value

Below is the referenceArray to compare and manipulate originalArray

const referenceArray = [
                       { name: 'animal', source: ['duck', 'cat'], target: ['water', 'ground'] },
                       { name: 'car', source: ['tata', 'kia'], target: ['tiago', 'sector'] },
                       { name: 'bike', source: ['honda', 'hero'], target: ['livo', 'xtream'] },
                       { name: 'vehicle', source: ['honda', 'hero'], target: ['hard', 'soft'] },
                       ];

And this is I want to change the array originalArray source and target values with the help of referenceArray source and target if it's matched take name value and set that value to originalArray source and target.

const originalArray = [
    { source: 'water', target: 'hero' },
    { source: 'tata', target: 'ground' },
    { source: 'livo', target: 'kia' },
    { source: 'hero', target: 'sector' },
  ];

Expected output that is required:

 const output1 = [
    { source: 'animal', target: ['bike', 'vehicle'] },
    { source: 'car', target: 'animal' },
    { source: 'bike', target: 'car' },
    { source: ['vehicle', 'bike'], target: 'car' },
  ];


 const output2 = [
    { source: 'animal', target: 'bike' },
    { source: 'animal', target: 'vehicle' },
    { source: 'car', target: 'animal' },
    { source: 'bike', target: 'car' },
    { source: 'vehicle', target: 'car' },
    { source: 'bike', target: 'car' },
  ];

Either output is acceptable, however output2 is preferred.

I'm confused how to achieve this format without getting key value conflicts.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The below may be one possible solution to achieve the desired objective (Output-2, from the question above).

Code Snippet

// get output in format-2
const getOutput2 = (refArr, arr) => (
  arr.flatMap(        // iterate using ".flatMap" to avoid nested result
    ({ source : osrc, target : otgt }) => (
      refArr.filter(      // filter for "source" using ref-arr
        ob => ob?.source.includes(osrc) || ob?.target.includes(osrc)
      ).sort(             // sort descending to match order of output-2
        (a, b) => b.name > a.name ? 1 : -1
      ).flatMap(          // for each "source", iterate using ".flatMap"
        ob => refArr.filter(    // filter for "target" 
          ob2 => ob2?.source.includes(otgt) || ob2?.target.includes(otgt)
        ).sort(           // sort ascending to match order of output-2
          (a, b) => a.name > b.name ? 1 : -1
        ).map(ob2 => ({         // construct the desired objective array
          source: ob.name, target: ob2.name
        }))
      )
    )
  )
);

// reference array from question
const referenceArray = [{
    name: 'animal',
    source: ['duck', 'cat'],
    target: ['water', 'ground']
  },
  {
    name: 'car',
    source: ['tata', 'kia'],
    target: ['tiago', 'sector']
  },
  {
    name: 'bike',
    source: ['honda', 'hero'],
    target: ['livo', 'xtream']
  },
  {
    name: 'vehicle',
    source: ['honda', 'hero'],
    target: ['hard', 'soft']
  },
];

// original array from question
const originalArray = [{
    source: 'water',
    target: 'hero'
  },
  {
    source: 'tata',
    target: 'ground'
  },
  {
    source: 'livo',
    target: 'kia'
  },
  {
    source: 'hero',
    target: 'sector'
  },
];

// log the results to console for verification
console.log(getOutput2(referenceArray, originalArray));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Explanation

Comments added inline in the snippet above

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