Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
Iterate through an array n number of times rotating items

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

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!