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

239
Visualizações
How to move the objects to the top inside array based on the matched key

I have an array of objects with different keys I want to move the objects to the top based on the key I want.

Given array based on the status: "Active" I want all the matched objects to be moved top

[
   {name: "abc", age: "20", status: "Active"}, 
   {name: "xyz", age: "21", status: "Inactive"}, 
   {name: "pqr", age: "22", status: "Active"}
]

Expected Output:

[
   {name: "abc", age: "20", status: "Active"}, 
   {name: "pqr", age: "22", status: "Active"}, 
   {name: "xyz", age: "21", status: "Inactive"}
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

let list = [{
  name: "abc",
  age: "20",
  status: "Active"
}, {
  name: "xyz",
  age: "21",
  status: "Inactive"
}, {
  name: "pqr",
  age: "22",
  status: "Active"
}]
list.sort((a, b) => (a.status !== "Active") ? 1 : -1)
console.log(list)

Produces the following output

[
  { name: 'pqr', age: '22', status: 'Active' },
  { name: 'abc', age: '20', status: 'Active' },
  { name: 'xyz', age: '21', status: 'Inactive' }
]
about 4 years ago · Juan Pablo Isaza Relatório

0

Arrays have method Array.sort where you can pass function that return 1, -1 or 0 which corresponds to how to move element of an array

const arr = [{
  name: "abc",
  age: "20",
  status: "Active"
}, {
  name: "xyz",
  age: "21",
  status: "Inactive"
}, {
  name: "pqr",
  age: "22",
  status: "Active"
}]
console.log(arr.sort((a, b) => (a.status === b.status) ? 0 : a.status === "Active" ? -1 : 1))

about 4 years ago · Juan Pablo Isaza Relatório

0

you can change your code like this.

function handleData(arr, status) {
   if(!arr || arr.length == 0) return
   for(let i=0; i<arr.length; i++) {
    let item = arr[i];
    if(item.status == status) {
      arr.splice(i, 1);
      arr.unshift(item)
    }
   }
}
let arr = [{name: "abc", age: "20", status: "Active"}, {name: "xyz", age: "21", status: "Inactive"}, {name: "pqr", age: "22", status: "Active"}]

handleData(arr, 'Active')

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