Struggling with sort in a function node

I must be missing something obvious here. I've dumbed my problem down to a simple function node containing the following:

const values = [
    { name: "a", size: 1 },
    { name: "b", size: 4 },
    { name: "c", size: 2 }
    ];
    
const sorted = values.sort((x, y) => y.size > x.size);
msg.payload = sorted;

return msg;

When I run it, the payload is unsorted. I'm expecting to get 'b' first, because it has the largest size However if I run the same code on an online JS compiler, it works as expected. If I change the sort to log what it's doing, I get the expected values:

const sorted = values.sort((x, y) => {
    var result = y.size > x.size;
    node.warn(y.name+ " "+y.size+" "+x.size+" "+result);
    return result;
});

This gives me:

a 1 4 false
b 4 2 true

google is your friend Sort an Array of Objects by Values of Object's Properites in JavaScript

You think very little of me to assume I have not Googled the crap out of it. The link you provided contains the same code I'm using.

Could you try instread:

const sorted = values.sort((x, y) => y.size - x.size);

The reasoning, the sort function sorts:

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

ie. it is not comparing the property values (in the way as one would expect).

That did it! Thanks, I knew it was something dumb I was doing.

1 Like

can you click mark as solution ?