0

I have the array ["a", "b", "c", "d", "e"] I need a function to shift abc to the end of the array - ["d", "e", "a", "b", "c"]

Chiru
  • 2,633
  • 1
  • 15
  • 28
MikeDiam
  • 111
  • 1
  • 9
  • Possible duplicate of [JavaScript Array rotate()](http://stackoverflow.com/questions/1985260/javascript-array-rotate) – user94559 Jul 14 '16 at 07:40

1 Answers1

4
function rotate(a, n) {
  // The modulo here is a performance optimization... rotating by the length of the array has no effect. E.g. in this example, rotating 8 is the same as rotating 3.
  for (var i = 0; i < n % a.length; i++) {
    a.push(a.shift());
  }
}

var a = ["a", "b", "c", "d", "e"];

rotate(a, 3);

console.log(a);

// Output:
// [ 'd', 'e', 'a', 'b', 'c' ]

EDIT

Non-destructive version using slice:

function rotate(a, n) {
  n %= a.length;
  return a.slice(n).concat(a.slice(0, n));
}

var a = ["a", "b", "c", "d", "e"];

console.log(rotate(a, 3));

// Output:
// [ 'd', 'e', 'a', 'b', 'c' ]

EDIT2

In response to the follow-up question in a comment, here's how you would copy the elements instead of moving them. (This is the non-destructive version.)

function copy(a, n) {
  n %= a.length;
  return a.concat(a.slice(0, n));
}

var a = ["a", "b", "c", "d", "e"];

console.log(copy(a, 3));

// Output:
// [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c' ]

Or here's an in-place version of copy:

function copy(a, n) {
  for (var i = 0; i < n % a.length; i++) {
    a.push(a[i]);
  }
}

var a = ["a", "b", "c", "d", "e"];

copy(a, 3);

console.log(a);

// Output:
// [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c' ]
user94559
  • 54,841
  • 6
  • 85
  • 93
  • Great! How to change this function in order to copy elements? To get output: ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c' ] – MikeDiam Jul 14 '16 at 07:57
  • Yes perfect. But if I use this function more than once - how can I copy to array next symbols? If I add "abc", at the next time I want to add "def" (depending on n parameter of your function) – MikeDiam Jul 14 '16 at 08:52
  • @MikeDiam I'm not sure what you mean. Could you give an example of the input and output you're expecting? E.g. input: `['a', 'b', 'c'], 3`, output: ??? – user94559 Jul 14 '16 at 09:03
  • I have done it by adding 3rd parameter to the function as s (times of function runs) a.push(a[i+n*(s-1)]); – MikeDiam Jul 14 '16 at 09:11