Find the values two arrays share
Permission checks, tag filters and "also bought" panels all reduce to the same question: which values appear in both lists?
Implement intersection(a, b). Return a new array holding every value from a that also appears in b, in the order they first appear in a, with duplicates removed so each shared value appears exactly once. Compare values the way a Set does: NaN matches NaN, but 1 does not match "1". If there is no overlap, or either array is empty, return an empty array. Never modify either input.
Arguments
aArray- The driving array — the order of the result follows this one.
bArray- Values are included only if they also appear here.
Returns
Array — A new array of each shared value, in order of first appearance in a, with duplicates removed.
Examples
intersection([1, 2, 3, 4], [2, 4, 6]);
// [2, 4]intersection([3, 1, 2], [1, 2, 3]); // [3, 1, 2] — order follows the first array
intersection([1, 1, 2, 2], [1, 2]); // [1, 2] — duplicates in a are collapsedWhat it has to do
- Include only values present in both arrays.
- Order the result by first appearance in
a. - Include each shared value only once, even if
arepeats it. - Match
NaNwithNaN, and keep1and"1"distinct. - Do not mutate either input array.
Stuck? The javascript course covers everything this challenge needs.
- 1.returns the shared values
- 2.orders by first appearance in the first array
- 3.removes duplicates from the first array
- 4.returns empty when nothing overlaps
- 5.matches NaN with NaN
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.