- Published on
Javascript: Given a array rotate it n times
- Authors
- Name
- Rakesh Yadav
- @jsbugpost
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 = 2rotateArray = [4, 5, 1, 2, 3]// For n = 3rotateArray = [3, 4, 5, 1, 2]// For n = 5rotateArray = [1, 2, 3, 4, 5]// For n = 0rotateArray = [1, 2, 3, 4, 5]Approach
- For every value of
nwe have to rotate input arrayn % inputArrayLengthtimes. - If
nis zero ornis multiple ofinputarray's length thenrotatedArraywill be same asinputarray.
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))