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

Viewed 29

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.

1 Answers

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

Related