JS Built-ins
← Array180 / 226
ArrayArray.prototype.sortintermediate

Array.prototype.sort() β€” sort objects by property

πŸ“– Usage Example
const users = [{name:'Bob'},{name:'Alice'},{name:'Carol'}]
users.sort((a, b) => a.name.localeCompare(b.name))
// β†’ [{name:'Alice'}, {name:'Bob'}, {name:'Carol'}]

Use sort() with a comparator that accesses a property to sort an array of objects.

Array.prototype.sort() β€” objects

You can sort an array of objects by accessing a property inside the comparator. This is one of the most common real-world uses of sort().

Challenge: Implement sortByAge(people) that returns a copy of the array sorted by age ascending.

sortByAge([{name:'Bob',age:30},{name:'Alice',age:25}])
// β†’ [{name:'Alice',age:25},{name:'Bob',age:30}]
πŸ’‘ Hints (2)
  • β€’ Access the property inside the comparator: `(a, b) => a.age - b.age`.
  • β€’ Use `.slice()` first to avoid mutating the input array.