Rotate an array
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return a new array with the items of `arr` rotated `k` steps to the right: each step moves the last item to the front. `k` can be larger than the length (rotating a 3-item array 4 steps is the same as 1 step) and can be negative, which rotates to the left. An empty array returns `[]`. Do not change `arr`.
What this exercise teaches
Rotating by the length changes nothing, so only k modulo the length matters. The double remainder turns a negative k into the equivalent rotation to the right, and two slices build the result without touching the input.
A hint if you get stuck
Reduce `k` to a number of steps between 0 and the length with the remainder operator. In JavaScript `%` keeps the sign of the left side, so use `((k % n) + n) % n`. Then join two slices.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Arrays and objects
- Group by a fieldFree
- Count by a fieldFree
- Remove duplicates by a fieldFree
- Split into chunksFree
- Zip two arraysFree
- Flatten one levelFree
- Pick some keysFree
- Sort by several keysFree
- Merge settingsFree
- Omit some keysFree
- Flatten to a depthFree
- Transpose a matrixFree
- Binary searchFree
- Two numbers that add upFree
- Values in both arraysFree