Scriptdrill

Level 2: Arrays and objects Exercise 30 of 76 Free

Values in both arrays

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return the values that appear in both `a` and `b`. Each value appears once in the result, in the order of its first appearance in `a`. Values are compared the way a `Set` compares them, so `1` and `"1"` are different and `NaN` equals `NaN`. Do not change the inputs.

What this exercise teaches

A Set gives constant-time membership tests and treats NaN as equal to itself, which indexOf does not. Walking a (not b) is what gives the result the order of a, and the second set removes the repeats.

A hint if you get stuck

Put `b` in a `Set` for fast lookups. Then go through `a`, keep the values the set has, and use a second set to skip values you have already taken.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Arrays and objects