Rotating an array - JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

Let’s say, we are required to write a JavaScript function that takes in an array and a number n and rotates the array by n elements

For example: If the input array is −

const arr = [12, 6, 43, 5, 7, 2, 5];

and number n is 3,

Then the output should be −

const output = [5, 7, 2, 5, 12, 6, 43];

Let’s write the code for this function −

Example

Following is the code −

// rotation
const arr = [12, 6, 43, 5, 7, 2, 5];
const rotateByOne = arr => {
   for(let i = 0; i < arr.length-1; i++){
      temp = arr[i];
      arr[i] = arr[i+1];
      arr[i+1] = temp;
   };
}
Array.prototype.rotateBy = function(n){
const { length: l } = this;
   if(n >= l){
       return;
   };
   for(let i = 0; i < n; i++){
       rotateByOne(this);
   };
};
const a = [1,2,3,4,5,6,7];
a.rotateBy(2);
console.log(a);

Output

Following is the output in the console −

[
 3, 4, 5, 6,
 7, 1, 2
]
raja
Updated on 14-Sep-2020 12:54:22

Advertisements