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

109
Visualizações
Move item to first position in array but keep order

I am a bit stuck with this problem. I am trying to write a function that takes an index and moves the item with that index in an array to the first position while maintaining the subsequential order of the other items.

const unorderedArr = [item1, item2, item3, item4]
const reorderArr = (i, arr) => { 
 ...
}

const reorderedArr = reorderArr(2, unorderedArr)
// [item3, item4, item1, item2]

Happy for any pointers!

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

0

You could use a swapping with the previous item until the index is zero.

const
    reorderArr = (array, i) => {
        while (i) {
            [array[i], array[i - 1]] = [array[i - 1], array[i]];
            i--;
        }
        return array;
    };

console.log(...reorderArr(['item1', 'item2', 'item3', 'item4'], 2));

about 4 years ago · Juan Pablo Isaza Relatório

0

slice(i) method will return an array after index(inceluded), and slice(0, i) will return an array from beginig of array to index (excluded). So result will be: ["item3","item4","item1","item2"]

const unorderedArr = ['item1', 'item2', 'item3', 'item4']
const reorderArr = (i, arr) => { 
  return [...arr.slice(i), ...arr.slice(0,i)];
}

const reorderedArr = reorderArr(2, unorderedArr);
console.log(reorderedArr)

about 4 years ago · Juan Pablo Isaza Relatório

0

Simply you can do like this

const unorderedArr = ["item1", "item2", "item3", "item4"];
const reorderArr = (i, arr) => {
  const movingElement = arr[i]; // get the element at index i
  arr.splice(i, 1); // remove the element from index i next to one ( item 3)
  arr.unshift(movingElement); // add the element to the beginning of the array
  return arr;
};

const reorderedArr = reorderArr(2, unorderedArr);
console.log("reorderedArr", reorderedArr);
//  [ 'item3', 'item1', 'item2', 'item4' ]

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