2

I would like to know the reason why this simple piece of code fails:

var arr = [1, 2, 3];
arr.push(arr[0]).shift();
console.log(arr);

it returns in firebug console "TypeError: arr.push(...).shift is not a function"

I think it happens because I invoke the shift() method not on an array but on the pushed element.

Is there a more elegant way to obtain the same result that,

var arr = [1, 2, 3];
arr.push(arr[0]);
arr.shift();
console.log(arr);

produce ?

Thanks in advance!

2
  • 1
    The close vote here is very strange... Please read the question til the end before voting. Commented May 6, 2015 at 15:44
  • If I made something wrong, I ask sorry. As you can see from my rep I'm not what you can call a veteran and maybe I am missing something. Commented May 7, 2015 at 19:32

3 Answers 3

3

From the MDN:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

arr.push(arr[0]) doesn't return the array but a number which, obviously, has no shift function.

To my knowledge, there's no simple expression pushing an element to an array and returning that array. But in your case you may simply reverse the operations and do

arr.push(arr.shift());
Sign up to request clarification or add additional context in comments.

1 Comment

@torazaburo No : concat returns a new array
1

I think it happens because I invoke the shift() method not on an array but on the pushed element.

Almost. push returns the new length of the array. A number obviously doesn't have a shift() method.

Your method of putting it on two lines is the simplest way.

1 Comment

"the simplest" ? Look at my answer ;)
0

Essentially this question is saying, can I somehow "elegantly" express the notion of moving the first item of an array to the end. Luckily, JS is a Turing-complete language, which allows us to define functions, so the "elegant" answer is just

rotate(arr)

Now it merely remains to define rotate. To rotate is to drop the first element in the result of adding the head element to the end:

function rotate(arr) { return drop(add(arr, head(arr))); }

Now drop is

function drop(arr) { return arr.shift(), arr; }

and head of course is

function head(arr) { return arr[0]; }

and add is

function add(arr, elt) { return arr.push(elt), arr; }

Another approach

I could also write a function to move n elements from position i to position j, using splice, as follows:

function move(arr, n, i, j) {
    arr.splice.apply(arr, [j-n+1, 0].concat(arr.splice(i, n)));
    return arr;
}

Then to rotate is to move one element at the beginning to the end:

function rotate(arr) { return move(arr, 1, 0, 999); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.