How can I check to see if one array is contained in another and return the missing values? I have found ways to do this in this post but none account for repeating values in the arrays. For example, I am trying to do something like this:
getDiff([1, 2, 3], [1, 2, 3, 4]) --> []
getDiff([1, 2, 2, 3], [1, 2, 3, 4]) --> [2]
getDiff(["A", "B", "C"], ["B", "B", "A", "C"]) --> []
getDiff(["B", "B", "B"], [3, 2, 1]) --> ["B", "B", "B"]
One possible approach:
Essentially, it's a two-step process: calculate the number of items in
diffed
array, then go throughsource
array one more time - and add a new item intodiff
resulting array for each copy missing indiffedCounter
. This particular implementation has one deficiency though: as it uses Object to collect the counts, it doesn't differentiate between3
as number and'3'
as a string when counting elements.This might be fixed in two different ways: either switch to Map (but that'll make code more complicated, as there's no such things as decrementing for map values) - or just use type prefixes when creating a counter keys. Here's the approach based on former: