Sort Object.entries when some values are undefined

Let's assume that you have the following object:

javascript
let ceos = {

    'elon': {money: 5000000000},
    'jeff': {money: 9000000000},
    'erik': {},
    'bill': {money: 1000000000}

}

You can try to sort the previous object:

javascript
let sorted = Object.entries(ceos).sort((a, b) => b[1].money > a[1].money ? 1 : b[1].money < a[1].money ? -1 : 0);

But the results aren't as you expect:

javascript
// [["jeff", {…}], ["elon", {…}], ["erik", {…}], ["bill", {…}]]

The reason is that there are undefined values in the object. Specifically, my money is undefined. 😎

If a value is undefined, the sort function will return 0, and you don't want to return 0 in each case. For example, if the function is comparing my money to the one of Elon, I expect the function to return 1.

How to solve it

Add an initial value to undefined fields:

javascript
let sorted = Object.entries(ceos).sort((a, b) => {

    let first  = a[1].money || 0;
    let second = b[1].money || 0;
    
    return second > first ? 1 : second < first ? -1 : 0
    
});

Here are the results:

javascript
// [["jeff", {…}], ["elon", {…}], ["bill", {…}], ["erik", {…}]]

Now, I'm at the end of the queue, but you never know where life will take you.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.