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
  • 100,735
  • 18
  • 158
  • 142
bryan
  • 8,879
  • 18
  • 83
  • 166

3 Answers3

5

Alternatively use forEach():

groups.forEach((element, index) => {
    // do what you want
});
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
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
  • 9,213
  • 4
  • 33
  • 37
2

Simply,

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

for(let g of groups) {
    console.log(groups.indexOf(g));
}
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54