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

259
Views
¿Cómo comparar y mostrar elementos similares en una matriz y mostrar el índice de cada uno junto con él?

Tengo un caso de uso en el que tengo que comparar dos elementos de una matriz y mostrar los elementos similares junto con el índice. Supongamos que tengo dos matrices, digamos,

 var array1 = ["One", "Two", "Three"]; var array2 = ["Four", "One", "Five"];

Quiero que la salida sea la siguiente:

 array1 One - 1 array2 One - 2

He escrito el siguiente fragmento de código para descubrir los elementos similares en ambas matrices, pero no puedo continuar con lo anterior.

 const filteredArray = array1.filter(value => array2.includes(value));

Por favor ayuda.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

  • Usando Array#reduce , itere sobre array1 mientras actualiza la lista resultante de elementos comunes que tienen el valor, el índice en array1 y el índice en array2
  • En cada iteración, usando Array#findIndex , obtenga el índice del valor actual en array2 , si existe, inserte un nuevo elemento en la matriz resultante.

 const array1 = ["One", "Two", "Three"], array2 = ["Four", "One", "Five"]; const filteredArray = array1.reduce((commonItems, value, index1) => { const index2 = array2.findIndex(e => e === value); if(index2 >= 0) { commonItems.push({ value, index1, index2 }); } return commonItems; }, []); console.log(filteredArray);

about 4 years ago · Santiago Trujillo Report

0

Puedes hacerlo de esta manera y almacenarlo en un objeto.

 var array1 = ["One", "Two", "Three"]; var array2 = ["Four", "One", "Five"]; let obj={ array1:[],array2:[] } array1.filter((value,i) => { if(array2.indexOf(value) !== -1){ console.log('value',value, array2.indexOf(value)) obj["array1"].push(`value - ${i + 1}`) obj["array2"].push(`value - ${array2.indexOf(value) + 1}`) } }); console.log(obj)

Producción

 { array1: [ 'value - 1' ], array2: [ 'value - 2' ] }
about 4 years ago · Santiago Trujillo Report

0

Aclaración: ¿Cómo debería ser One - 2 para array2? Como One está en el índice 0 en array1

Según tengo entendido, simplemente puede lograr esto usando Array.forEach() junto con el método Array.indexOf() .

Demostración en vivo :

 var array1 = ["One", "Two", "Three"]; var array2 = ["Four", "One", "Five"]; array1.forEach(item => { if (array2.indexOf(item) !== -1) { console.log(item, array2.indexOf(item)); } }); array2.forEach(item => { if (array1.indexOf(item) !== -1) { console.log(item, array1.indexOf(item)); } });

about 4 years ago · Santiago Trujillo 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!