23

I'm having a hard time finding a dupe of this question, but I assume it's been asked before....

If I add three items to a Set:

var s = new Set();
undefined
s.add(1); s.add(2); s.add(3);
Set(3) {1, 2, 3}

... How can I find out the index of an item?

There is no indexOf method for Set and I'm not sure if iterating over the Set is the best way. I've tried using the forEach API but can neither break nor return from this function:

  if (s.size < cells.length) {
    var count = 0;
    s.forEach(function (value) {
      if (cell.id.slice(0, -5) == value) {
        break;  //return fails here too...
      }
      count ++;
    });
    return count;
  }
JacobIRR
  • 8,545
  • 8
  • 39
  • 68
  • 1
    check https://stackoverflow.com/questions/3330193/early-exit-from-function for your 'break'/'return' part – treecon Jun 19 '17 at 20:56
  • not relevant to my question ^^ about getting an item's index in a Set – JacobIRR Jun 19 '17 at 20:57
  • @JacobIRR It is relevant to the 'break'/'return' part. As you say, if you could break the function, you would have your solution. – treecon Jun 19 '17 at 20:58
  • @JacobIRR it's the spread operator (...) all it does is copy all the elements in the set into the array e.g `const numbers = [1, 2, 3];` `console.log(sum(...numbers));` // expected output: 6 `console.log(sum.apply(null, numbers));` // expected output: 6 – John Munyi Jun 12 '20 at 12:14

1 Answers1

27

The purpose of Sets is not so much to give an order number, but if you need one, the pragmatic solution is to temporarily turn it into an array with the spread syntax:

count = [...s].indexOf(cell.id.slice(0, -5));

If for some reason you prefer looping, then use some instead of forEach:

[...s].some(function (value) {
  if (cell.id.slice(0, -5) == value) {
    return true; // this will stop the iteration
  }
  count ++;
});

Or why not use the ES6 for of loop:

for (const value of s) {
  if (cell.id.slice(0, -5) == value) {
    break; // this will stop the iteration
  }
  count ++;
}

NB: Although the use of the old-style for ... in loop is discouraged for use with arrays, this does not hold for the for ... of loop.

trincot
  • 317,000
  • 35
  • 244
  • 286