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"]
4
Answers
What I might do is create a dictionary of counts of the values in
array2
.Then use a loop to process each element of
array1
. If the count is greater than 0, replace and decrement. Otherwise, do nothing.Very efficient, even for long lists (O(N+M)).
Just count and decrement the count.
You could check if your array already contains the resulting product, and then not add that.
You can just use a
Set
to store all the char’s that have already been used. And use the.has
to to check, finally add the used chars using.add
.eg.