4

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.

1
  • I'm not sure about React, but in javascript there is for-in that goes through indices Commented Apr 1, 2018 at 17:37

3 Answers 3

6

Alternatively use forEach():

groups.forEach((element, index) => {
    // do what you want
});
Sign up to request clarification or add additional context in comments.

2 Comments

I get .forEach() is not a function
@bryan Do you have the same definition of groups as in your question?
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);
}

Comments

2

Simply,

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.