Nick WEI
Nick WEI

Reputation: 33

How can I drop out of the loop?

I try to write a function which can rotate the array to the left,eg 1,2,3,4,5,6,7,8,9 and turn to 4,5,6,7,8,9,1,2,3. At first place, I use this funciton below ,but the result is 4,2,3,7,5,6,1,8,9. Therefore, I think it does not drop out of the loop because it only executes once in the loop. Please anyone could help me with this? Any help would be appreciated! Thanks in advance.

var a =[1,2,3,4,5,6,7,8,9];
var len =a.length;
for (i=0;i<3;i++ )
{   
    var b = a[i];
    var j = i;
    for(k=0;k<a.length;k++)
      {
        j+=3;
        if(j<a.length)
        {
            a[i] = a[j];
            i=j;
        }
        else {
            j-=3;
            a[j]=b;
            break;
        }

    }   
}

console.log(a);

Upvotes: 1

Views: 204

Answers (2)

Atish Shakya
Atish Shakya

Reputation: 561

If you want algorithm with no array methods you can do it like this :

var a=[1,2,3,4,5,6,7,8,9];
console.log(a);

//Iteration of rotation (Here rotated left 3 times) this can be as many as you want.
for(let i=0;i<3;i++){
  //Store 'First Member' and 'Last Index' of array
  let last = a.length - 1;
  let first = a[0];

  //Loop to store every (n+1)th term to nth except the last one
  for(let j=0;j<last;j++){
    a[j] = a[j+1];
  }

  //Finally add first item to last index
  a[last] = first; 
}

console.log(a);

Upvotes: 0

Martin
Martin

Reputation: 16433

I'm not sure of the approach you are using, but using shift and push will achieve this very easily:

var a =[1,2,3,4,5,6,7,8,9];
var len = a.length;
for (i = 0; i < 3; i++) {
  a.push(a.shift());
}

console.log(a);

Output:

4,5,6,7,8,9,1,2,3

shift removes the first item from an array. Here are some docs for it.

push pushes an item onto the end of an array. Here are some docs for it.

Upvotes: 1

Related Questions