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

115
Vistas
Move array objects within itself according to a certain object's property

Suppose we have an array of objects and we want it to move some objects with a certain property to the beginning of the array, For more clarity I will give an example:

let arr = [
  {id:5 , tag: "X" , name:"mohsen"},
  {id:1 , tag: "A" , name:"hasan"},
  {id:3 , tag: "P" , name:"ali"},
  {id:8 , tag: "D" , name:"mehran"},
  {id:4 , tag: "C" , name:"nima"},
  {id:12 , tag: "A" , name:"keivan"},
  {id:6 , tag: "P" , name:"pedram"},
  {id:17 , tag: "X" , name:"masoud"},
  {id:20 , tag: "D" , name:"hadi"},
];

at this moment if we want to move objects with tag:"P" to beginning of array like below:

[
  {id: 3 ,name: "ali",tag: "P"}, 
  {id: 6,name: "pedram",tag: "P"},
  {id: 5,name: "mohsen",tag: "X"},
  {id: 1,name: "hasan",tag: "A"},
  {id: 8,name: "mehran",tag: "D"}, 
  {id: 4,name: "nima",tag: "C"}, 
  {id: 12,name: "keivan",tag: "A"},
  {id: 17,name: "masoud",tag: "X"},
  {id: 20,name: "hadi",tag: "D"}
]

What should we do?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

for more description, at the first we map on array then for every item of array we check that item[propName] === propValue condition if it is true then we cut this item from its place with const b = arr.splice(index , 1); and put it at beginning of array with arr.splice(place,0,...b); , the place variable track new index of beginning of array.

let arr = [
  {id:5 , tag: "X" , name:"mohsen"},
  {id:1 , tag: "A" , name:"hasan"},
  {id:3 , tag: "P" , name:"ali"},
  {id:8 , tag: "D" , name:"mehran"},
  {id:4 , tag: "C" , name:"nima"},
  {id:12 , tag: "A" , name:"keivan"},
  {id:6 , tag: "P" , name:"pedram"},
  {id:17 , tag: "X" , name:"masoud"},
  {id:20 , tag: "D" , name:"hadi"},
];



function reorderListByProp(propName , propValue) {
  const rem = [];
  let place = 0;
  arr.map((item , index) => {
    if(item[propName] === propValue) {
      const b = arr.splice(index , 1);
      arr.splice(place,0,...b);
      place++;
    }
  });

  return arr;
}

console.log(reorderListByProp('tag' , 'P'));

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