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

108
Visualizações
¿Cómo recopilar la intersección y ambos complementos de dos matrices dentro de una tarea?

arreglos-

 const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6];

Matrices vacías -

 const matches1 = []; const matches2 = []; const unmatches1 = [];

Círculo -

 for (const line of source) { const line2Match = target.find((line2) => { const isMatch = line === line2; return isMatch; }); if (line2Match) { matches1.push( line ); matches2.push(line2Match); } else { unmatches1.push(line); } }

Esta es la salida en este momento -

[ 1, 1, 1, 4 ] ​​​​​en partidos1

[ 3 ] ​​​en​​​​unmatches1

[ 1, 1, 1, 4 ] ​​​​​en partidos2

La salida deseada -

[ 1, 4 ] ​​​​​en ​​​​​​​partidas1

[ 1, 1, 3 ] ​​​​​en ​​​​​​​desigualdades1

[ 1, 4 ] ​​​​​en ​​​​​​​partidos2

Lo que me gustaría agregar es que cuando la source coincida con target , el valor se eliminará de la matriz de target , ¿cómo puedo lograrlo?

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

0

El OP...

"Lo que me gustaría agregar es que cuando la fuente coincida con el destino, el valor se eliminará de la matriz de destino, ¿cómo puedo lograrlo?"

Uno tenía que mutar activamente la matriz de target cortando el elemento común de ella, lo que al final hace que target se convierta en el complemento relativo de la source en target ... comúnmente/vulgo... la diferencia del objetivo .

Una de las causas podría aplicar una copia superficial del target como parte del valor inicial de una tarea de reduce para no mutar la referencia del target original en sí ...

 function collectIntersectionAndComplements(collector, sourceItem) { const { targetDiff } = collector; const targetIndex = targetDiff .findIndex(targetItem => targetItem === sourceItem); if (targetIndex === -1) { // collect the relative complement of target // in source ... vulgo ... the source difference. (collector.sourceDiff ??= []) .push(sourceItem) } else { // collect the intersection of both source and target ... (collector.intersection ??= []) .push( // ... by rejecting the common item from the original // target, thus actively mutating the latter, which leads // to ending up additionally with the relative complement // of source in target ... vulgo ... the target difference. targetDiff.splice(targetIndex, 1)[0] ); } return collector; } const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; const { intersection, sourceDiff, targetDiff, } = source.reduce(collectIntersectionAndComplements, { targetDiff: [...target] }); console.log({ source, target, intersection, sourceDiff, targetDiff });
 .as-console-wrapper { min-height: 100%!important; top: 0; }

@ heyheyhey2 ... Por cierto, si uno estaba hablando de la teoría simple de conjuntos , entonces no se permitían valores duplicados (idénticos) dentro de cada matriz/lista/conjunto. Los conjuntos siempre tienen que presentar solo valores únicos.

about 4 years ago · Juan Pablo Isaza Relatório

0

Solo para partidos 1: (similar para partidos 2)

 const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; let matches1 = source.reduce((res, curr) => { if (target.includes(curr) && !res.includes(curr)) { res.push(curr); } return res; }, [] ); console.log(matches1) //[1,4]

Para no coincidencias1:

 let unmatches1 = source.reduce((res, curr) => { if ((target.includes(curr) && res[0].includes(curr)) || !target.includes(curr)) { res[1].push(curr); } if (target.includes(curr)) { res[0].push(curr) } return res; }, [[],[]] )[1] console.log(unmatches1) //[1,1,3]

Para lograr el resultado de unmatches2 [2,5,6], simplemente reemplace la fuente y el destino en la entrada, o en el código, o extienda el código aunque tenga ambas salidas. Es simple.

about 4 years ago · Juan Pablo Isaza Relatório

0

Tenga en cuenta que para un solo paso, ambas matrices deben haberse clasificado en orden ascendente.

 function go(){ const a = [0,1, 1, 1, 3, 4, 6,8,10]; const b = [-3,-4,1, 2, 4, 5, 6,25,26]; let nomatcha=[]; let match=[]; let nomatchb=[]; let i=0,j=0; while(true){ if(i>=a.length){ for (;j<b.length;j++) nomatchb.push(b[j]); break; } else if (j>=b.length){ for (;i<a.length;i++) nomatcha.push(a[j]); break; } else if(a[i]==b[j]){ match.push(a[i++]); j++; } else if (a[i]<b[j]){ let val=a[i++]; if(nomatcha.length==0)nomatcha.push(val); else if(val != nomatcha[nomatcha.length-1]) nomatcha.push(val); } else if (b[j]<a[i]){ let val=b[j++]; if(nomatchb.length==0)nomatchb.push(val); else if(val != nomatchb[nomatchb.length-1]) nomatchb.push(val); } } console.log("match: "+match); console.log("nomatcha: "+nomatcha); console.log("nomatchb: "+nomatchb); }

}

Producción:

coincidencia: 1,4,6 nomatcha: 0,1,3,8,10 nomatchb: -3,-4,2,5,25,26

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