Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda