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']