markzzz
markzzz

Reputation: 47995

Remove element from the end and add to the beginning

I tried this function :

var myArray=new Array("1", "2", "3", "4");
var value=myArray.pop();
myArray.push(value);

but I'd like to remove 4 from the end and add it to the beginning. So should be 4 1 2 3. So a LIFO methodology using push and pop... How can I do it?

Upvotes: 1

Views: 526

Answers (4)

Skylar Anderson
Skylar Anderson

Reputation: 5703

var myArray=new Array("1", "2", "3", "4");
myArray.unshift(myArray.pop());

Upvotes: 3

gislikonrad
gislikonrad

Reputation: 3581

You almost had it...

This is how you do it:

var myArray=new Array("1", "2", "3", "4");
var value=myArray.pop();
myArray.unshift(value);

Upvotes: 3

J0HN
J0HN

Reputation: 26951

Use unshift method (reference)

var myArray=new Array("1", "2", "3", "4");
var value=myArray.pop();
myArray.unshift(value);

Upvotes: 5

Igor Dymov
Igor Dymov

Reputation: 16460

var myArray=new Array("1", "2", "3", "4");
var value=myArray.pop();
myArray.splice(0, 0, value);

Upvotes: 1

Related Questions