Avatar ·

Sorting an array of objects by property values in JavaScript

Hello everyone! I'm a beginner in JavaScript and encountered a problem when sorting an array of objects. I have an array of users, each object contains a name and age: ```javascript const users = [ { name: 'Anna', age: 25 }, { name: 'Ivan', age: 30 }, { name: 'Maria', age: 22 }, { name: 'Petr', age: 28 } ]; ``` I need to sort this array by age (from youngest to oldest), and then by name in alphabetical order. I tried using the `sort()` method directly, but it doesn't work as expected — it sorts as strings, and objects are not compared correctly. I've read that `sort()` accepts a comparison function, but I can't figure out how to write it for objects. I tried something like `users.sort((a, b) => a.age - b.age)`, but the result is strange — sometimes it sorts, sometimes