How to usedestructuring assignment and the spread operator in Javascript
In this approach, we can use destructuring assignment along with the spread operator to achieve left rotation by one in an array. We first destructure the array into two parts: the first element and the rest of the elements. Then, we use the spread operator to combine the rest of the elements with the first element placed at the end.
Example:
function leftRotateByOne(arr) {
if (arr.length <= 1) {
return arr;
}
const [first, ...rest] = arr;
return [...rest, first];
}
const arr = [1, 2, 3, 4, 5];
console.log("Rotated Array:", leftRotateByOne(arr));
Output
Rotated Array: [ 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