- 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
n
we have to rotate input arrayn % inputArrayLength
times. - If
n
is zero orn
is multiple ofinput
array's length thenrotatedArray
will be same asinput
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.
for loop
Implementation using 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}
ES6 Array.reduce method
Implementation using 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))