Anu
Anu

Reputation: 630

How to make a for loop dynamic?

I am have 2 arrays like [2,3] and [1000,1200,500,600,1600] . I need to write a for loop for this like.

1.start index from 0 and end index at 2.

2.start time from 2 and end index with sum of first 2 element (2+3)= 5.

var arr = [2,3];
for(var i = 0; i<arr.length;i++)
{
    //this loop runs 2 time
    for(var j = 0 ; j < 2 ; j++)//for the first time
    for(var j = 2 ; j < 5 ; j++)//for the second time

}

How to make this dynamic for loop? Can someone please help me code?

Upvotes: 1

Views: 105

Answers (4)

Jason Goemaat
Jason Goemaat

Reputation: 29234

If you want it to be generic, i.e. you have the array arr containing counts of elements to process, you could do it like this:

var arr = [2,3];

// k is the index into the second array, initialize to 0 here
for(var i = 0, k = 0; i < arr.length;i++)
{
    //this loop runs for each element in the arr[] array
    for(var j = 0 ; j < i; j++, k++) // increment k
    {
        // k is now the value you want:
        // first time through the loop 0, 1
        // second time through the loop 2, 3, 4
    }
}

Another tweak would be to just keep track of the start element if it's important for j to be the value:

var arr = [2,3];
var start = 0;
for(var i = 0; i < arr.length; i++)
{
    var end = start + arr[i]; // end is 2,5 in sample
    for(var j = start ; j < end; j++)
    {
        // first time through the loop 0, 1
        // second time through the loop 2, 3, 4
    }
    start = end; // now start at the next index, 0,2 in sample
}

Upvotes: 1

John R
John R

Reputation: 2791

Hope you are expecting this.

var arr = [2, 3];
for (var i = 0; i < arr.length; i++) {
    //this loop runs 2 time
    if (i == 0) {
       //for the first time
       for (var j = 0; j < arr[0]; j++) { }
    } else if (i == 1) {
       //for the second time
       var totalSum = arr[0] + arr[1];
       for (var j = arr[0]; j < totalSum; j++) //for the second time
        { }
   }
}

Upvotes: 1

EngineerCamp
EngineerCamp

Reputation: 671

This would do what you want and would be extendible.

var arr = [2,3];
var sum = 0;
for(var i = 0; i<arr.length;i++)
{
   sum += arr[i]
   if (i === 0) {
      for(var j = 0 ; j < arr[0] ; j++) 
         // Do first thing
   }
   if (i > 0) {
      for(var j = arr[0] ; j < sum ; j++)
         // Do second thing
   }
}

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Do something like this:

var k = 0;
for(var j = 0 ; j < 2 ; j++) {
 k+=arr[j];
}//for the first time
    for(var i = 2 ; i < k ; i++) {
       //other code
}

Upvotes: 0

Related Questions