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

108
Vistas
Filtering two arrays for matching values into new array in Javascript

I'm trying to match two arrays and extract the matching values into a new array while keeping it in the same order as the second array. For example:

let strArr1 = ['a', 'p', 'p', 'l', 'e']; 
let strArr2 = ['p','p','a','e', 'l', 'l', 'k'];
let newArr = [];
// Wanted output: ['p', 'p', 'a', 'e', 'l']

So what I'm trying to do here is remove the extra characters in the second array. The code I've come up with so far:

for (let i=0; i < strArr1.length; i++){
for (let j=0; j < strArr2.length; j++){
if (strArr1[i]==strArr2[j]){
  newArr.push(strArr2[i])
  }
 }
}

For some reason, the output becomes:

['p', 'p', 'p', 'a', 'a', 'e', 'e', 'l']

I've also tried the filter method. It's closer to the results I want.

const newArr = strArr2.filter(value => strArr1.includes(value));

But the output becomes:

['p', 'p', 'a', 'e', 'l', 'l']
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can try something like this

strArr1 = strArr1.reduce((acc, v)=> ({ ...acc, [v]: (acc[v] ? (++acc[v]) : 1) }), {})
strArr2.filter(v => !!(strArr1[v]--)  )
about 4 years ago · Juan Pablo Isaza Denunciar

0

There are two mistakes in your code though, you are pushing strArr2[i] in the newArr although, you used j to iterate over strArr2. And when you find a match to push into newArr, you need to break the loop and move to the next element in strArr2.

In order to keep the order in strArr2 you need to change the order of the for loop,

for (let i=0; i < strArr2.length; i++){
  for (let j=0; j < strArr1.length; j++){
     if (strArr1[j]==strArr2[i]){
        newArr.push(strArr2[i])
        j += strArr1.length;
     }
  }
}

The complexity is O(n^2) You can optimize the code by doing the following,

let strArr1 = ['a', 'p', 'p', 'l', 'e']; 
let strArr2 = ['p','p','a','e', 'l', 'l', 'k'];
let newArr = [];
// Wanted output: ['p', 'p', 'a', 'e', 'l']

newArr = strArr2.filter(item => strArr1.includes(item));

console.log(newArr);

['p', 'p', 'a', 'e', 'l', 'l'] is correct output as there is two l in the strArr2.

If you want to match each value once, you can remove the value from strArr1 after finding a match.

let strArr1 = ['a', 'p', 'p', 'l', 'e']; 
let strArr2 = ['p','p','a','e', 'l', 'l', 'k'];
let newArr = [];
console.log('abc');

newArr = strArr2.reduce((prev, curr) => {

            if(strArr1.includes(curr)) {
               prev.push(curr);
               strArr1.splice(strArr1.indexOf(curr), 1);
            }
            return prev;
         }, []);
         
console.log(newArr);

about 4 years ago · Juan Pablo Isaza Denunciar

0

const newArr = strArr2.filter(value => strArr1.includes(value) && arr.splice(arr.indexOf(value), 1));

This works :)

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