logo
logo

Rotate Array

Lesson
Given an array of
n
elements and an integer
k
, write a function called
rotateArray
that rotates the array
k
steps to the right. For example, given the array
[1,2,3,4,5,6,7]
and
k = 3
, the output should be
[5,6,7,1,2,3,4]
.

Consider how you might implement this by just using Array builtin methods as well as traditional loops.

Traditional Looping Solution

Another way to solve the problem "Rotate Array" is to use a while loop along with
splice()
and
unshift()
methods. In this approach, we use a while loop to repeatedly remove the last element of the array using the splice method and then add it to the beginning of the array using the unshift method. Here is an example of this solution in code:
function rotateArray(arr, k) {
    while (k > 0) {
        // remove last element of the array
        let removedElement = arr.splice(-1, 1);
        // add removed element to the beginning of the array
        arr.unshift(removedElement[0]);
        k--;
    }
    return arr;
}

Video Solution:

Using Array Builtins

Use the
splice()
method to remove the last k elements of the array, and then use the
unshift()
method to add them to the beginning of the array.

Here's an example of this solution in code:

function rotateArray(arr, k) {
    // remove the last k elements of the array
    let removedElements = arr.splice(-k, k);
    // add the removed elements to the beginning of the array
    Array.prototype.unshift.apply(arr, removedElements);
    return arr;
}
Notice the use of
Array.prototype.unshift.apply(arr, removedElements);
rather than
arr.unshift(removedElements);
arr.unshift(removedElements)
would add the entire
removedElements
array as a single element to the beginning of the
arr
array, resulting in an array that looks like
[[5,6,7], 1,2,3,4]
.
Array.prototype.unshift.apply(arr, removedElements)
on the other hand, uses the
apply()
method to apply the
unshift()
method to the
arr
array, and pass the
removedElements
array as separate arguments. This allows each element of the
removedElements
array to be added individually to the beginning of the
arr
array, resulting in an array that looks like
[5,6,7,1,2,3,4]
.
In other words,
arr.unshift(removedElements)
will add the
removedElements
array as a single element to the
arr
array, while
Array.prototype.unshift.apply(arr, removedElements)
will add each element of the
removedElements
array individually to the
arr
array.