1

Edit: The link provided below by faintsignal is the most applicable answer. It not only explains why this behavior occurs but offers a solution to the stated problem.

I've got an array that I would like to determine if all elements are equal to a single value. The following code seems like it should work, but it doesn't. Can anyone explain?

var array1 = ['foo', 'bar', 'baz'];
var array2 = ['foo', 'foo', 'foo'];

//I expect this to be false and it is
new Set(array1) == new Set(['foo']);

//I expect this to be true and it is not
new Set(array2) == new Set(['foo']);

Any information would be most welcome!

5
  • 5
    Possible duplicate of Why are two identical objects not equal to each other? and here's a how-to compare, also linked in the duplicate Commented Jan 6, 2017 at 16:32
  • It doesn't matter if you have two completely identical objects - object1 == object2 will only evaluate to true if they are in fact the exact same object. Commented Jan 6, 2017 at 16:35
  • You are comparing objects and they are not the same in the way you might think they should be. Have a look here Commented Jan 6, 2017 at 16:37
  • You should check if the size of the set is 1. Commented Jan 6, 2017 at 16:37
  • 2
    Also a dupe of: comparing ECMA6 sets for equality Commented Jan 6, 2017 at 16:38

1 Answer 1

1

Check if the size of the set is one:

new Set(array2).size === 1

As other answers/comments have already mentioned,

new Set(array2) == new Set(['foo'])

returns false because different objects are not equal.

You could in theory check for the equivalence of new Set(array2) and new Set(['foo']) using the techniques in questions referred to in the comments, but you don't need to do this, since checking if the size is 1 does exactly what you need.

Sign up to request clarification or add additional context in comments.

2 Comments

His underlying question is not to check for set equality. He wants to check that all the elements in the array are identical. Checking for set equality is just an idea he had for solving his problem. Checking if the set size is one is precisely the way to check that all the elements in the array are identical.
I'm really sorry, you are absolutely right. I didn't get the underlying question until now, but actually it is exactly what you describe...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.