Rotating an array - JavaScript

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 = l){
       return;
   };
   for(let i = 0; i 

Output

Following is the output in the console −

[
 3, 4, 5, 6,
 7, 1, 2
]
Updated on: 2020-09-14T12:54:22+05:30

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements