0

I want to make a function that changes an array so the order stays the same, but the position of the indexes is changed: for example

1, 2, 3, 4, 5

becomes

2, 3, 4, 5, 1

My problem is that I am getting an infinite loop, and I think that it has something to do with the code i != one Also, what is the problem with i != one in the code?

var switchArray = function(arrayOne){
  //save the original arrayOne[0] with var one
  var one = arrayOne[0];
  //loop around until i = the original [0]; i originally = one - the length of the array so it equals the last index.
  for(var i = arrayOne[arrayOne.length - 1]; i != one;){
    // set var b = var i ( the last index of the array)
    var b = arrayOne[arrayOne.length - 1];
    //delete the last index of the array
    arrayOne.pop(arrayOne[arrayOne.length - 1]);
    //add var b to the array as the first index
    arrayOne.unshift(b);
  }
  return arrayOne;
}

1 Answer 1

1

You can do it in one line:

var array = [1, 2, 3, 4, 5];
array.push(array.shift());

console.log(array); // => [2, 3, 4, 5, 1] 

See on JSFiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.