I have two arrays:
const array1 = ["A", "S", "S", "G"]; // multiple occurrences of 'S'.
const array2 = ["S", "F", "J", "A"]; // single occurrence of 'S'.
I want to match the array2
with array1
for each of the instances. So I made a function:
const matchedArray = (array1, array2) => {
let finalArray = [];
array1.forEach((char, idx) => array2.includes(char) ? finalArray[idx] = `✅${char}` : finalArray[idx] = char);
return finalArray;
}
But as you can understand that .includes()
matches with all the instances of that character. So a single instance of "S"
on the array2
matches with the two S
s of the array1
. So the function is returning:
["✅A", "✅S", "✅S", "G"]
How can I achieve the finalArray
be like:
["✅A", "✅S", "S", "G"]