Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  98] [ 1]  / answers: 1 / hits: 32495  / 7 Years ago, mon, june 19, 2017, 12:00:00

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;
}

More From » javascript

 Answers
3

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.


[#57381] Saturday, June 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
;