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

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

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