Compare two arrays as sets
A multi-select gives you an array of ids. Deciding whether to refetch means asking whether the selection really changed — and ["a", "b"] versus ["b", "a"] is not a change, nor is ["a", "a", "b"] versus ["a", "b"].
Implement sameSet(a, b). Return true when the two arrays contain exactly the same distinct values, ignoring order and ignoring how many times each value appears, and false otherwise. Values are compared the way a Set compares them, so NaN matches NaN but 1 does not match "1". Two empty arrays are the same set. An empty array and a non-empty one are not. Never modify either input.
Arguments
aArray- The first array to compare.
bArray- The second array to compare.
Returns
boolean — true when both arrays contain the same distinct values, ignoring order and duplicates.
Examples
sameSet([1, 2, 3], [3, 2, 1]); // true — order does not matter
sameSet([1, 1, 2], [2, 1, 1, 1]); // true — duplicates do not mattersameSet([1, 2], [1, 3]); // false — different distinct values
sameSet([NaN], [NaN]); // true — Set-style equality matches NaN
sameSet([1], ["1"]); // false — Set-style equality keeps types distinctWhat it has to do
- Ignore ordering when comparing.
- Ignore duplicate values within either array.
- Return
truefor two empty arrays. - Match
NaNwithNaN, and keep1and"1"distinct. - Do not mutate either input array.
Stuck? The javascript course covers everything this challenge needs.
- 1.ignores ordering
- 2.ignores duplicates
- 3.detects a genuinely different set
- 4.treats two empty arrays as the same set
- 5.matches NaN with NaN but not 1 with "1"
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.