AniUI Academy

Compare two arrays as sets

mediumArrays & Objects+250 XPPractice

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 matter
sameSet([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 distinct

What it has to do

  • Ignore ordering when comparing.
  • Ignore duplicate values within either array.
  • Return true for two empty arrays.
  • Match NaN with NaN, and keep 1 and "1" distinct.
  • Do not mutate either input array.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.