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!

baao
  • 71,625
  • 17
  • 143
  • 203
biagidp
  • 2,175
  • 3
  • 18
  • 29
  • 5
    Possible duplicate of [Why are two identical objects not equal to each other?](http://stackoverflow.com/questions/11704971/why-are-two-identical-objects-not-equal-to-each-other) and here's a [how-to compare](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects), also linked in the duplicate – baao Jan 06 '17 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*. – Tyler Roper Jan 06 '17 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](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Noelkd Jan 06 '17 at 16:37
  • You should check if the size of the set is 1. –  Jan 06 '17 at 16:37
  • 2
    Also a dupe of: [comparing ECMA6 sets for equality](http://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality) – faintsignal Jan 06 '17 at 16:38

1 Answers1

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.

baao
  • 71,625
  • 17
  • 143
  • 203
  • 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. –  Jan 08 '17 at 04:34
  • 1
    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... – baao Jan 08 '17 at 08:24