Harsha Jayamanna
Harsha Jayamanna

Reputation: 2258

Use "for..of" to iterate through only a section of the array

This is my code to iterate through the array.

for (let name of group['controls']) {
   //code
}

If the length of the group['controls'] array is X, how to iterate through 0 to X-2?

Upvotes: 0

Views: 27

Answers (1)

ADreNaLiNe-DJ
ADreNaLiNe-DJ

Reputation: 4919

The for..in and the for...of loop will iterate the entire array so from 0 to length - 1 (or X-1 in your question).

To stop a for...of loop to a given index, you have to add a condition inside the loop and call a break, like this:

for (let index of group['controls']) {
    let name = group['controls'][index];
    if(index == group['controls'].length -2) {
        break;
    }
}

Additionnal information:

  • for...in loop iterate on values: names in your examples.
  • for...of loop iterate on the indexes of the array: group['controls'] in your example.

Upvotes: 1

Related Questions