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

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

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 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