Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native for loop getting index [duplicate]

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.

like image 459
bryan Avatar asked Sep 02 '25 06:09

bryan


2 Answers

Alternatively use forEach():

groups.forEach((element, index) => {
    // do what you want
});
like image 78
Code-Apprentice Avatar answered Sep 04 '25 20:09

Code-Apprentice


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);
}
like image 26
Axnyff Avatar answered Sep 04 '25 20:09

Axnyff