How to useshift() and push() method in Javascript
In this approach, Using shift() removes the first element, and push() adds it to the end, achieving a left rotation by one position in an array.
Syntax:
if (arr.length <= 1) {
return arr;
}
let elem1 = arr.shift();
arr.push(elem1);
Example: In this example, we are using the above-explained approach.
function ratationalArray(arr) {
if (arr.length <= 1) {
return arr;
}
let elem1 = arr.shift();
arr.push(elem1);
return arr;
}
let arr1 = [15, 16, 17, 18, 19];
let result = ratationalArray([...arr1]);
console.log("Original Array:", arr1);
console.log("Array after Left Rotation:", result);
Output
Original Array: [ 15, 16, 17, 18, 19 ] Array after Left Rotation: [ 16, 17, 18, 19, 15 ]
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.