Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!