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

95
Visualizações
How to move multiple elements in an array from one position to another

I have an array with 8 elements. How do I move the last 4 elements to the front?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Array.prototype.concat() combined with Array.prototype.slice():

const arr = [1, 2, 3, 4, 5, 6, 7, 8]
const result = arr.slice(4).concat(arr.slice(0, 4))

console.log(result)

A more dynamic version:

const arr = [1, 2, 3, 4, 5, 6, 7, 8]
const half = arr.length / 2 
const result = arr.slice(half).concat(arr.slice(0, half))

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use a combination of the Array.prototype.slice method and the Spread operator.

First spread the last four elements from the original array and then spread the remaining elements from the beginning.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  newArr = [...arr.slice(-4), ...arr.slice(0, -4)];

console.log(newArr);

You can also do it by just using Array.prototype.Splice but remember it mutates the original array.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.splice(0, 0, ...arr.splice(-4));

console.log(arr);

about 4 years ago · Juan Pablo Isaza Relatório

0

If you're ok mutating the array (rather than creating a new one) splice the last four elements, and then unshift them to the start of the array.

(Note: splice returns an array, so you need to spread the elements out.)

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
arr.unshift(...arr.splice(-4));
console.log(arr);

about 4 years ago · Juan Pablo Isaza 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