DEV Community

Discussion on: How to shift array position in vanilla JavaScript

Collapse
 
kennethtruyers profile image
Kenneth Truyers

I very much like the plain ES5 solution by @lexlohr . Here's another, more generic version that lets you rotate an array by a variable number of positions:

const rotateArray = (array, count) => {
  const arr = [...array];

  count = (count || 0) % arr.length;
  if (count < 0)  count += arr.length;

  var removed = arr.splice(0, count);
  arr.push.apply(arr, removed);

  return arr;
}