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.
Arguments
aArray- The source list to filter.
bArray- Items of
awhose 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 directlydifferenceBy(
[{ 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
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.
Stuck? The javascript course covers everything this challenge needs.
- 1.subtracts primitives with the default key function
- 2.subtracts objects by a computed key
- 3.keeps duplicates that survive
- 4.returns a copy when nothing is subtracted
- 5.does not mutate the first array
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.