2

How do you efficiently scroll an array with looping either acting on the array itself or returning a new array

arr = [1,2,3,4,5]

i want to do something like this:

arr.scroll(-2)

arr now is [4,5,1,2,3]
johowie
  • 2,475
  • 6
  • 26
  • 42

1 Answers1

5

Use Array.slice:

> arr.slice(-2).concat(arr.slice(0, -2));
[4, 5, 1, 2, 3]

You can then generalize it and extend Array.prototype with the scroll function:

Array.prototype.scroll = ​function (shift) {
    return this.slice(shift).concat(this.slice(0, shift));
}​;

> arr.scroll(-2);
[4, 5, 1, 2, 3]
Community
  • 1
  • 1
João Silva
  • 89,303
  • 29
  • 152
  • 158