
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Finding the rotation of an array in JavaScript
We are required to write a JavaScript function that takes in an array and a number n.
Our function should rotate the array by n elements, i.e., take n elements from the front and put them to the end.
The only condition here is that we have to do this without using any extra space in memory −
For example −
If the input array is the following,
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];
Example
Following is the code −
const arr = [12, 6, 43, 5, 7, 2, 5]; const num = 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); }; }; arr.rotateBy(num); console.log(arr);
Output
This will produce the following output in console −
[ 2, 5, 12, 6, 43, 5, 7 ]
- Related Articles
- Finding the mid of an array in JavaScript
- Finding the index position of an array inside an array JavaScript
- Finding the majority element of an array JavaScript
- Finding degree of subarray in an array JavaScript
- Finding the longest string in an array in JavaScript
- Finding unlike number in an array - JavaScript
- Finding sum of a range in an array JavaScript
- Finding product of an array using recursion in JavaScript
- Finding all possible subsets of an array in JavaScript
- Finding the first redundant element in an array - JavaScript
- JavaScript Finding the third maximum number in an array
- Finding unique string in an array in JavaScript
- Finding missing element in an array of numbers in JavaScript
- Finding desired sum of elements in an array in JavaScript
- Finding matching pair from an array in JavaScript

Advertisements