Rotate an array by n positions in JavaScript
Intermediate · 4 min read
Rotating a list means moving every item along by some number of places, with the items that fall off one end coming back on the other. Rotate [1, 2, 3, 4, 5] left by 2 and you get [3, 4, 5, 1, 2]. Image carousels, turn order in a game and "whose shift is next" rotas all work this way.
In this tutorial you will write rotate(values, n). It handles an n bigger than the list and a negative n, which rotates the other way. On the way you will meet a surprise in JavaScript's % operator that causes bugs in every kind of wrap-around code. You need to know what an array and a function are.
The idea: cut and swap
Rotating left by 2 is the same as cutting the list after the first 2 items and swapping the two pieces:
[1, 2 | 3, 4, 5] cut after 2 items
[3, 4, 5 | 1, 2] swap the pieces
slice does the cutting. slice(2) copies from position 2 to the end, and slice(0, 2) copies the first two items. The spread syntax ... unpacks an array's items into a new array, so you can join the pieces:
const nums = [1, 2, 3, 4, 5];
console.log(nums.slice(2)); // [ 3, 4, 5 ]
console.log(nums.slice(0, 2)); // [ 1, 2 ]
console.log([...nums.slice(2), ...nums.slice(0, 2)]); // [ 3, 4, 5, 1, 2 ]
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
46 Rotate an array by n places
fairMove every element of a list n places to the left, wrapping around. Handle an n larger than the list and a negative n.
Stuck? Three hints, smallest first
- 1.
n % lengthhandles an n larger than the list. - 2. JavaScript’s
%keeps the sign of the left operand, so-1 % 5is-1, not4. - 3.
((n % len) + len) % lenis the standard fix for a positive remainder.
Step 1: rotate by a small n
Turn the cut-and-swap into a function:
function rotate(values, n) {
return [...values.slice(n), ...values.slice(0, n)];
}
console.log(rotate([1, 2, 3, 4, 5], 2)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate([1, 2, 3, 4, 5], 7)); // [ 1, 2, 3, 4, 5 ]
The first line is right. The second is wrong: rotating 5 items by 7 should be the same as rotating by 2, because the first 5 steps bring everything back to the start.
Step 2: wrap a big n with %
The remainder operator % gives what is left after dividing. 7 % 5 is 2: take away whole trips round the list and 2 steps remain.
function rotate(values, n) {
const shift = n % values.length;
return [...values.slice(shift), ...values.slice(0, shift)];
}
console.log(rotate([1, 2, 3, 4, 5], 7)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate([1, 2, 3, 4, 5], -1)); // [ 5, 1, 2, 3, 4 ]
7 now works, and so does -1: the last item moved to the front. It looks finished. But it only works by luck, and the next step shows why.
Step 3: the negative remainder trap
Print the shift that % gives for a negative n:
console.log(-1 % 5); // -1
console.log(-6 % 5); // -1
In math class, "-1 mod 5" is 4. JavaScript's % is a remainder, and the remainder keeps the sign of the number on the left. So -1 % 5 is -1.
A shift of -1 isn't a real position in the list. slice happens to rescue you, because it reads a negative position as "count from the end". Reading an item with square brackets doesn't. Ask for the item that should end up first, and you get nothing:
const nums = [1, 2, 3, 4, 5];
const shift = -1 % nums.length;
console.log(nums[shift]); // undefined
Rotating left by -1 is the same as rotating left by 4, so you want the shift to be 4, a real position. The fix is a well-known pattern: take the remainder, add the length, and take the remainder again.
console.log(((-1 % 5) + 5) % 5); // 4
console.log(((7 % 5) + 5) % 5); // 2
For a negative remainder, adding 5 brings it into the 0 to 4 range. For a positive one, adding 5 pushes it too far, and the second % 5 brings it back. Either way you end up between 0 and 4.
Step 4: put it together, and guard the empty list
An empty list has length 0, and n % 0 is NaN, so the shift would be meaningless. Return an empty list straight away instead:
function rotate(values, n) {
const len = values.length;
if (len === 0) return [];
const shift = ((n % len) + len) % len;
return [...values.slice(shift), ...values.slice(0, shift)];
}
const nums = [1, 2, 3, 4, 5];
console.log(rotate(nums, 2)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate(nums, 7)); // [ 3, 4, 5, 1, 2 ]
console.log(rotate(nums, -1)); // [ 5, 1, 2, 3, 4 ]
console.log(rotate(nums, -6)); // [ 5, 1, 2, 3, 4 ]
console.log(rotate(nums, 0)); // [ 1, 2, 3, 4, 5 ]
console.log(nums); // [ 1, 2, 3, 4, 5 ]
Every case is right, and nums itself is untouched, because slice and spread build a new array.
The full solution
The answer panel has the finished rotate, prints rotations by 2, 7 and -1, and shows -1 % 5 for itself. The checks cover a full rotation, large and negative values, zero, an empty list and the untouched original. Press Run to see the output.
function rotate(values, n) {
const len = values.length;
if (len === 0) return [];
// JavaScript's % keeps the sign of the left side, so normalise it.
const shift = ((n % len) + len) % len;
return [...values.slice(shift), ...values.slice(0, shift)];
}
const nums = [1, 2, 3, 4, 5];
console.log('by 2 :', rotate(nums, 2));
console.log('by 7 :', rotate(nums, 7), '(same as 2)');
console.log('by -1:', rotate(nums, -1));
// The trap this avoids:
console.log('-1 % 5 in JavaScript is', -1 % 5, '-- not 4');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('rotate left by two', rotate(nums, 2), [3, 4, 5, 1, 2]);
test('a full rotation is the identity', rotate(nums, 5), nums);
test('more than a full rotation wraps', rotate(nums, 7), [3, 4, 5, 1, 2]);
test('negative rotates the other way', rotate(nums, -1), [5, 1, 2, 3, 4]);
test('a large negative also wraps', rotate(nums, -6), [5, 1, 2, 3, 4]);
test('zero changes nothing', rotate(nums, 0), nums);
test('an empty list is fine', rotate([], 3), []);
test('the original is untouched', (() => { const a = [1, 2, 3]; rotate(a, 1); return a; })(), [1, 2, 3]);
test('JavaScript modulo really does go negative', -1 % 5, -1);
-1 % 5 being -1 rather than 4 is the whole exercise. JavaScript's % is a remainder, not a mathematical modulo: it takes the sign of the left operand. ((n % len) + len) % len is the idiom that gives you a genuine modulo, and it is worth memorising because this bites in every wrap-around problem — clock arithmetic, circular buffers, grid wrapping.
Common mistakes
- Assuming
%is always positive.-1 % 5is-1in JavaScript. Use((n % len) + len) % lenwhenever a value has to wrap around. - Moving one step at a time. A loop that rotates by one place
ntimes works, but fornof a million it does a million moves. The%line gets the same answer in one go. - Changing the original. Rotating with
shiftandpushin a loop moves items in the caller's array. Build a new one instead.
Try it yourself
- Write
rotateRight(values, n)using yourrotate. (Hint: right by n is left by -n.) - Use
((i % len) + len) % lento make a "previous" button for a 4-image carousel that goes from image 0 back to image 3. - Rotate the letters of a string:
'lagos'by 2 should give'gosla'.