DEV Community

Discussion on: Array Rotation in JS

Collapse
 
vkoonline profile image
Medet Tleukabiluly ✎

return arr.slice(d).concat(arr.slice(0, d)) is enough

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari • Edited

Thank you i will try this
Can you please explain this code?
I am getting a bit confused with it

Collapse
 
peerreynders profile image
peerreynders • Edited
function rotateLeft(d, arr) {
  const endToBegin = arr.slice(d);
  const beginToEnd = arr.slice(0, d);
  return endToBegin.concat(beginToEnd);
}

const array = [1, 2, 3, 4, 5, 6];
const rotation = 2;
console.log(rotateLeft(rotation, array)); // [3, 4, 5, 6, 1, 2]
Enter fullscreen mode Exit fullscreen mode

Better?

Array.prototype.slice() - JavaScript | MDN

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

favicon developer.mozilla.org
Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Got it thank you for explaining 😉

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Also Number.parseInt(arr.length % d) could be useful in case the number is greater than the arr length.

const completeRotations = arr.length / d;

let extraSteps = Number.parseInt(arr.length % d);
Enter fullscreen mode Exit fullscreen mode

With that you can simply do a single complete rotation and keeo going the extra steps instead of failing 😁

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank you i will try this as well 😉