How to usethe map() method in Javascript
In this approach, we are using the map method for Left Rotate by One in an array involves creating a new array where each element is derived from the previous elementās position, wrapping around to the start. The first element becomes the last, and the array order is shifted left by one position.
Syntax:
map((element, index, array) => { /* ā¦ */ })
Example: In this example, we are using the above-explained approach.
function rotationFunction(arr) {
if (arr.length <= 1) {
return arr;
}
return arr.map((_, index, array) =>
array[(index + 1) % array.length]);
}
let arr1 = [1, 2, 3, 4, 5];
let result = rotationFunction(arr1);
console.log("Original Array:", arr1);
console.log("Array after Left Rotation :", result);
Output
Original Array: [ 1, 2, 3, 4, 5 ] Array after Left Rotation : [ 2, 3, 4, 5, 1 ]
JavaScript Program for Left Rotate by One in an Array
In this article, we are going to learn about left Rotation by One in an Array by using JavaScript, Left rotation by one in an array means shifting all elements from one position to the left, with the last element moving to the first position. The order of elements is cyclically rotated while maintaining their relative sequence.
There are several methods that can be used to left Rotate by One in an Array in javascript, which are listed below:
Table of Content
- Approach 1: Using the map() method
- Approach 2: Using slice() method
- Approach 3: Using shift() and push() method
- Approach 4: Using for loop
- Approach 5: Using destructuring assignment and the spread operator
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us