1

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
  • 80,295
  • 14
  • 134
  • 129
bryan
  • 7,656
  • 12
  • 65
  • 136

3 Answers3

3

Alternatively use forEach():

groups.forEach((element, index) => {
    // do what you want
});
Code-Apprentice
  • 69,701
  • 17
  • 115
  • 226
2

Simply,

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

for(let g of groups) {
    console.log(groups.indexOf(g));
}
Matus Dubrava
  • 10,269
  • 2
  • 24
  • 38
2

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
  • 7,275
  • 2
  • 26
  • 31