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

95
Views
How do I sort objects in arrays that don't always have a property?

Here is an example of my array:

const database = [
  { name: item1, errors: true },
  { name: item2, factors: { rank: 1 } },
  { name: item3, factors: { rank: 2 } },
  { name: item2, errors: true },
];

Here is what I want:

const sorted_database = [
  { name: item3, factors: { rank: 2 } },
  { name: item2, factors: { rank: 1 } },
  { name: item1, errors: true },
  { name: item2, errors: true },
];

While this part of the post might not be necessary, to clarify, I want the array to be sorted with the rank descending and if it's undefined to remain in some random order below. I do however, need to keep all of the data. I have tried just using sort, and got an error for undefined property. I then tried making two different sets, but for some reason they rarely matched each other. Looking for an elegant solution someone perhaps knows to this that I haven't yet learned.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could look for factors first and then sort by rank.

const
    database = [{ name: 'item1', errors: true }, { name: 'item2', factors: { rank: 1 } }, { name: 'item3', factors: { rank: 2 } }, { name: 'item2', errors: true }];

database.sort((a, b) =>
    !a.factors - !b.factors ||
     b.factors?.rank - a.factors?.rank
);

console.log(database);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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!