Published on

Javascript: Given a array rotate it n times

Authors

Write a function that will take an array and n as argument and return a n times rotated array.

For Example:

const arr = [1, 2, 3, 4, 5]
const rotatedArray = rotateArray(arr, 2)
// OUTPUT
// For n = 2
rotateArray = [4, 5, 1, 2, 3]
// For n = 3
rotateArray = [3, 4, 5, 1, 2]
// For n = 5
rotateArray = [1, 2, 3, 4, 5]
// For n = 0
rotateArray = [1, 2, 3, 4, 5]

Approach

  1. For every value of n we have to rotate input array n % inputArrayLength times.
  2. If n is zero or n is multiple of input array's length then rotatedArray will be same as input array.

first element in roatedArray will be elemet at index inputArrayLength - n % inputArrayLength of input array.

2nd element in roatedArray -------- inputArrayLength - n % inputArrayLength + 1 of input array.

3rd element in roatedArray -------- inputArrayLength - n % inputArrayLength + 2 of input array.

Similarly of ith element in roatedArray will be element at index (inputArrayLength - n % inputArrayLength + i)%inputArrayLength of input array.

Javascript Code

We can implement above approach many ways. In this article we will implement using normal for loop and ES6 Array.reduce method. We will not mutate input array.

Implementation using for loop

function rotateArray(input, n) {
const rotatedArray = []
for (let i = 0; i < input.length; i++) {
const rotatedIndex = (input.length - (n % input.length) + i) % input.length
rotatedArray.push(input[rotatedIndex])
}
return rotatedArray
}

Implementation using ES6 Array.reduce method

function rotateArray(input, n) {
return input.reduce((rotatedArray, value, index) => {
rotatedArray.push(input[(input.length - (n % input.length) + index) % input.length])
return rotatedArray
}, [])
}
console.log(rotateArray([1, 2, 3, 4, 5], 2))

Output

Rotate Array Javascript