methuselah
methuselah

Reputation: 13206

Shifting all the values in an array one index higher with the displaced last element placed as the first element

I'm struggling with the below code in JS please help:

Currently trying to get

[20,30,40,50]

to be

[50,20,30,40]

any tips?

Here is the code I have so far below!

// A program to shift all the values in an array one index higher, with the displaced last element being placed as the first element

var test = [20,30,40,50];

for (i=0; i<test.length;i++)
{
    alert(test[i] + " is currently index: " + [i]); 
    }

test[0] = test[test.length-1];

for (i=0; i<test.length;i++)
{
    alert(test[i] + " is now index: " + [i+1]); 
    }

Upvotes: 2

Views: 583

Answers (3)

Luo
Luo

Reputation: 162

Another way is using splice(), not pretty enough though

arr.splice(0, 0, arr.splice(arr.length-1, 1));

Upvotes: 1

alex
alex

Reputation: 490213

Just to be different...

a.slice(-1).concat(a.slice(0, -1));

jsFiddle.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160191

Just do this:

a.unshift(a.pop());

Upvotes: 7

Related Questions