Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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]); 
    }
like image 349
methuselah Avatar asked Jul 08 '26 01:07

methuselah


1 Answers

Just do this:

a.unshift(a.pop());
like image 95
Dave Newton Avatar answered Jul 10 '26 15:07

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!