Scriptdrill

Level 2: Arrays and objects Exercise 31 of 76 Free

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 exercise

More exercises in Arrays and objects