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 exerciseMore exercises in Arrays and objects
- Group by a fieldFree
- Count by a fieldFree
- Remove duplicates by a fieldFree
- Split into chunksFree
- Zip two arraysFree
- Flatten one levelFree
- Pick some keysFree
- Sort by several keysFree
- Merge settingsFree
- Omit some keysFree
- Flatten to a depthFree
- Transpose a matrixFree
- Binary searchFree
- Two numbers that add upFree
- Rotate an arrayFree