Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda