1

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);

2
  • Surround your existing code with an additional loop that iterates n times? Commented Jun 14, 2022 at 15:17
  • adding to derpirscher's comment. instead of push maybe explicitly set newArr[i-1]=arr[i] and then after each iteration set arr = [...newArr] Commented Jun 14, 2022 at 15:20

2 Answers 2

1

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;
}

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.