0

I have an array with 5 values. I want to cycle through the array so that the values index all increase by one and the item in the final position moves to the front of the array. So for example:

[1,2,3,4,5]

Would become:

[5,1,2,3,4]

In python it is as simple as this:

lst = [1, 2, 3, 4, 5]
lst = lst[-1] + lst[:-1]

However I am not able to figure out how to do this in javascript

What is the correct syntax for performing this in javascript?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Maurio
  • 172
  • 3
  • 13

2 Answers2

3

One way to do it would be like this:

const test = [1,2,3,4,5];

test.unshift(test.pop());

console.log(test)
2

You can use pop to get the last entry from the array, and unshift to push it on the front:

array.unshift(array.pop());

Live Example:

const array = [1,2,3,4,5];
console.log("before", array);
array.unshift(array.pop());
console.log("after", array);
.as-console-wrapper {
    max-height: 100% !important;
 }

Going the other way, shift shifts the array over and gives you the first entry, and push adds to the end.

array.push(array.shift());

Live Example:

const array = [5,1,2,3,4];
console.log("before", array);
array.push(array.shift());
console.log("after", array);
.as-console-wrapper {
    max-height: 100% !important;
 }
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • And if i wanted to do the reverse? (move elements to the left?) – Maurio Jan 27 '20 at 14:26
  • 1
    @Maurio - [`shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) shifts the array over and gives you the first entry, and [`push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) adds to the end. – T.J. Crowder Jan 27 '20 at 14:27
  • 1
    @Maurio array.push(array.shift()); – Ashkan Pourghasem Jan 27 '20 at 14:27