Subtract one list from another by key
"Show me the recommended products the user has not already added" is a subtraction between two arrays of objects. Reference comparison fails, because the two lists hold different object instances for the same product.
Implement differenceBy(a, b, keyFn). Compute the key of every item in b using keyFn, then return a new array of the items in a whose key is not among them. keyFn defaults to the identity function, so calling it with two arrays of primitives compares the values directly. Order is preserved from a, and duplicates in a are kept — this filters, it does not deduplicate. Keys are compared the way a Set does. If b is empty, the result is a copy of a. Never modify either input.
What it has to do
- Keep items of
awhose key does not appear among the keys ofb. - Default
keyFnto the identity function when it is not supplied. - Preserve the order of
aand keep its duplicates. - Return a copy of
awhenbis empty. - Do not mutate either input array.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.