4229

I have an array of JavaScript objects:

var objs = [ 
    { first_nom: 'Laszlo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

How can I sort them by the value of last_nom in JavaScript?

I know about sort(a,b), but that only seems to work on strings and numbers. Do I need to add a toString() method to my objects?

1
  • 5
    Case sensitive or case insensitive sort? Commented Dec 10, 2022 at 22:18

61 Answers 61

1 2
3
0

I know there are already plenty of answers, including those with localeCompare ones, but if you don't want to/can't use localeCompare for some reason, I would suggest you to use this solution instead of the ternary operator solution:

objects.sort((a, b) => (a.name > b.name) - (a.name < b.name));

Someone could say that it's not obvious what this code is doing, but in my opinion the ternary operator is worse. If one ternary operator is readable enough, two ternary operators one embedded into another — really hard to read and ugly. One-line code with just two comparison operators and one minus operator is very simple to read and thus to reason about.

Sign up to request clarification or add additional context in comments.

Comments

1 2
3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.