Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of item in Javascript Set

Tags:

javascript

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;
  }
like image 929
JacobIRR Avatar asked Jun 19 '17 20:06

JacobIRR


1 Answers

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.

like image 167
trincot Avatar answered Oct 24 '22 16:10

trincot