3

This is probably a super simple question, but I have the following:

let groups = [{}, {}, {}];

for(let g of groups) {
    console.log(g);
}

How do I get the index number of said group? Preferably without doing a count.

Mayank Shukla
  • 92,299
  • 16
  • 152
  • 142
bryan
  • 8,279
  • 15
  • 74
  • 148

3 Answers3

5

Alternatively use forEach():

groups.forEach((element, index) => {
    // do what you want
});
Code-Apprentice
  • 76,639
  • 19
  • 130
  • 241
3

Instead of looping through groups, you could loop through groups.entries() which returns for each element, the index and the value.

Then you can extract those value with destructuring:

let groups = [{}, {}, {}];

for(let [i, g] of groups.entries()) {
    console.log(g);
}
Axnyff
  • 8,235
  • 3
  • 31
  • 36
2

Simply,

let groups = [{}, {}, {}];

for(let g of groups) {
    console.log(groups.indexOf(g));
}
Matus Dubrava
  • 12,128
  • 2
  • 31
  • 49