How to sort an array of objects by a string property in JavaScript?
Hello everyone! I'm new to JavaScript and encountered a problem when sorting an array of objects. I have an array of users, each containing a name and age. I need to sort this array by name (a string property) in alphabetical order.
Here's an example of my code:
```javascript
const users = [
{ name: 'Иван', age: 25 },
{ name: 'Петр', age: 30 },
{ name: 'Анна', age: 22 },
{ name: 'Мария', age: 28 }
];
users.sort((a, b) => a.name - b.name);
console.log(users);
```
But this code doesn't work — the array is not sorted, or is sorted incorrectly. I understand that the `-` operator doesn't work with strings, but how do you correctly compare strings? I tried using `a.name > b.name`, but that also didn't give the desired result: the order of elements remained the same.
No answers yet.
Log in to leave an answer
Blogs