Hello Guys today i will show you how to rotate left 1-d array in JS
The rotation will depent on the input like 2 means rotation.
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left.
Let's get started...
function rotateLeft(d, arr) {
// Write your code here
let newArray = []
if(d > arr.length){
return "Rotation value cannot be bigger than array length"
}
else{
for(let i=0;i<d;i++){
newArray.push(arr.shift(i))
}
let rotated = arr.concat(newArray)
return rotated
}
}
let array = [1,2,3,4,5,6]
let rotation = 2
console.log(rotateLeft(rotation,array))
Output -
[ 3, 4, 5, 6, 1, 2 ]
Working
- Inside the function , we have created an empty array which will hold the elements after rotation.
- After that we provide a condition where we will check if the number of rotation is greater than the array length or not.
- In the else part , we used the for loop up to the number of rotations (exclusive, means if the rotation value is 4 then the for loop will be executed from 0-3)
- Inside the loop we removed the element from the starting up to the rotation value - 1(because array index starts from 0) and then pushed those removed elements in the empty array we have created.
- In the end we have combined the original array with array containing the removed elements which will come at the end.
If you have a better approach or solution to this code , please mention it in the comment section.
THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--
Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo
https://dev.to/shubhamtiwari909/e-quotes-3bng
https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl