AniUI Academy

Subtract one list from another by key

mediumArrays & Objects+250 XPPractice

"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.

Arguments

aArray
The source list to filter.
bArray
Items of a whose key matches any key in here are dropped.
keyFn(item) => any
Called on each item to derive its identity. Defaults to the identity function.

Returns

Array — A new array of items from a whose key is not among the keys of b. Order and duplicates from a are preserved.

Examples

differenceBy([1, 2, 3], [2]);
// [1, 3] — default keyFn compares primitives directly
differenceBy(
  [{ id: 1 }, { id: 2 }],
  [{ id: 2 }],
  (item) => item.id,
);
// [{ id: 1 }]

A keyFn lets you subtract by a derived identity instead of by reference.

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.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.