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

180
Visualizações
Javascript sort array of objects alphabetically AND put first objects with value

I'm trying to sort this data which contains various arrays of objects, the console.log of myData is something like:

[
  {
    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx'
  },
  {
    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'
  }
]
[
  {
    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'
  }
]

I'm trying to sort it alphabetically (based on value of name) and if the object has the parameter url , put it at the beginning.

So the output would be:

    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'

    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'

    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx'

what I tried is this, and many variations of it, but it doesn't work:

var myData = props?.data

console.log(props?.data)

if(props.data){
  // those with url first, then alphabetically
  myData = props.data.sort(function(a, b){
    return b.url? 1 || (a.name < b.name) : -1;
  })
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use !url as a number (0 or 1) and subtract them:

const arr = [{"name":"Cdb","image":"xxx","coll":"xxx"},{"name":"Bcd","image":"xxx","coll":"xxx","url":"myurl"},{"name":"Abc","image":"xxx","coll":"xxx"}]

arr.sort((a, b) => !a.url - !b.url || a.name.localeCompare(b.name));
  
console.log(arr)

This is saying that if exactly one of both has the url argument, that one should come first. Otherwise (if both have it, or neither have it) then the name is decisive.

This way, when multiple objects have the url argument, they will also be ordered among themselves by name.

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