4

I am trying to take an array and have it loop around itself. I already found a simple solution for having it loop around itself backwards:

array = ['Dog', 'Cat', 'Animal', 'Pig']
array[array.length] = array[0];
array.shift();

This as expected turns out as ['Cat', 'Animal', 'Pig', 'Dog']. How would I make it do the opposite in a similar manner. By doing the opposite I mean turning out ['Pig', 'Dog', 'Cat', 'Animal']. I have tried to find the opposite of .shift() for this but can't find anything. Thank you for your time.

Ethan Coe
  • 47
  • 1
  • 4

2 Answers2

4

You could Array#pop

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

and Array#unshift.

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

var array = ['Dog', 'Cat', 'Animal', 'Pig'];

array.push(array.shift());
console.log(array); // ["Cat", "Animal", "Pig", "Dog"]

array = ['Dog', 'Cat', 'Animal', 'Pig'];

array.unshift(array.pop());
console.log(array); // ["Pig", "Dog", "Cat", "Animal"]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

It looks like you're looking for a rotate function:

Array.prototype.rotate = (function() {
    // save references to array functions to make lookup faster
    var push = Array.prototype.push,
        splice = Array.prototype.splice;

    return function(count) {
        var len = this.length >>> 0, // convert to uint
            count = count >> 0; // convert to int

        // convert count to value in range [0, len)
        count = ((count % len) + len) % len;

        // use splice.call() instead of this.splice() to make function generic
        push.apply(this, splice.call(this, 0, count));
        return this;
    };
})();

a = [1,2,3,4,5];
a.rotate(1);
console.log(a.join(',')); //2,3,4,5,1
a.rotate(-1);
console.log(a.join(',')); //1,2,3,4,5
a.rotate(-1);
console.log(a.join(',')); //5,1,2,3,4
Nick is tired
  • 6,860
  • 20
  • 39
  • 51