I have an array like [1,2,3,4,5] and i have the total number to rotate the array like 3. So, after the first rotation the array should be [2,3,4,5,1]. This way the array should keep rotating n number of times which is given. I have a solution to rotate the array which is shown below but i can't do this n number of times. Here's what i have done :
function rotateLeft(arr, n) {
var newArr = [];
for( let i=1; i< arr.length; i++){
newArr.push(arr[i]);
}
newArr.push(arr[0]);
console.log(newArr);
}
rotateLeft([1,2,3,4,5], 3);
Push the first element of an array to the end within a while loop
const original = [1,2,3,4,5];
console.log(`original: [${
original}], rotated: [${
rotateLeft(original, 3)}]`);
function rotateLeft(arr, n) {
// if you want to mutate the original arr
// omit cloning
const clone = [...arr];
while (n--) {
clone.push(clone.shift());
};
return clone;
}
Since you don't rotate the array in place, but instead create a new array, you can do it simpler:
function rotateLeft(arr, n) {
n %= arr.length;
return [...arr.slice(n), ...arr.slice(0, n)];
}
// generate an array with numbers
const arr = [...Array(20).keys()];
console.log(...arr);
// rotateLeft by 8
console.log(...rotateLeft(arr, 8));
// rotateLeft by -22 (rotateRight by 22)
// since arr.length === 20
// same as rotateLeft by -2
// same as rotateLeft by 18
console.log(...rotateLeft(arr, -22));