0

I had issue with set.has() method. I have a set that has a two dimensional array that shows the index of another two dimensional array. When I want to check that the set contains an index it always returns false.

Here is the code:

var indexes = new Set();
while (indexes.size < 10) {
    indexes.add(randomIndex());
}

function randomIndex() {
    i = Math.floor(Math.random() * 9);
    j = Math.floor(Math.random() * 11);
    return [i, j];
}

indexes.has([i,j]);

console image

Veve
  • 6,643
  • 5
  • 39
  • 58
  • 1
    And what's your problem specifically? Please update the question with that information. – Carcigenicate Dec 09 '16 at 13:35
  • I have a set that I stored in it a two dimensional array like [i,j]. when I check that the set has a value like `indexes.has([i,j])` it returns _flase_ while it has it. The attached image shows the console log. – Poorya Hosseini Dec 09 '16 at 13:51
  • @PooryaHosseini you cannot make such a determination with a Set instance. Two different arrays can have the same values in them, but they're still two **different** arrays as far as the Set is concerned. – Pointy Dec 09 '16 at 13:58
  • In general `[] !== []` (and `[1, 2] !== [1, 2]`, etc) in JavaScript, hence `set.add([1, 2])` followed by `set.has([1, 2])` will produce `false`. What you are trying to do is generally impossible through the method you've chosen. – VLAZ Dec 09 '16 at 14:09

2 Answers2

1

The identity comparisons made for members of a Set will be based on object identity. If you add [5, 10] to the Set, the set doesn't care about 5 or 10. What matters is that the array is a particular object. You cannot determine whether the Set contains an array with a 5 and a 10 by inquiring about a different array of [5, 10], because that different array is, well, different. No two objects are equal to each other.

To put it another way, you can create as many arrays like [5, 10] as you like and add them all to a single Set instance, because each of the arrays will be a distinct object.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    Just as further clarification: http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript - basically arrays (and objects in general) don't equal each other unless they are literally the _same_ object, not if they merely look similar. – VLAZ Dec 09 '16 at 13:42
  • Thanks for the link it is helpful. – Poorya Hosseini Dec 09 '16 at 16:44
0

I wrote this function and it worked. Maybe it would be helpful for someone else reached to this question:

function setHas(set, value) {
  var has = false;
  set.forEach(function (element) {
    if ((element[0] === value[0]) && (element[1] === value[1])) {
      has = true;
    }
  });
  return has;
}