AniUI Academy
medium+250 XPPractice

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 a whose key does not appear among the keys of b.
  • Default keyFn to the identity function when it is not supplied.
  • Preserve the order of a and keep its duplicates.
  • Return a copy of a when b is empty.
  • Do not mutate either input array.

Your workspace

Try it yourself
Loading playground...

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.