JavaScriptArray
JavaScriptArray

Reputation: 140

keep order in array, but change position of indexes

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;
}

Upvotes: 0

Views: 51

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42028

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.

Upvotes: 1

Related Questions