Sorting Objects by Property
You'll learn how to sort an array of objects based on a specific property inside each object.
The Core Idea
So far you've sorted numbers and strings, but real-world JavaScript often involves arrays of objects—like users, products, or tasks. To sort these meaningfully, you need to write a comparator function that reaches into each object and compares a specific property.
Think of it like organizing a bookshelf: instead of comparing books directly, you might sort them by title, author, or publication year. Your comparator function extracts that specific property and compares those values.
How It Works
The comparator function receives two objects (let's call them a and b). Inside the function, you access the property you want to sort by, then return the comparison result just like with numbers:
const users = [
{ name: 'Charlie', age: 35 },
{ name: 'Alice', age: 28 },
{ name: 'Bob', age: 42 }
];
// Sort by age (ascending)
users.sort((a, b) => a.age - b.age);
// Result: Alice (28), Charlie (35), Bob (42)
// Sort by name (alphabetical)
users.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
// Result: Alice, Bob, Charlie
For numeric properties, subtraction works perfectly. For strings, use comparison operators to determine ordering. Remember: return negative to put a before b, positive to put b before a, or zero if they're equal.
Key Takeaway: Sort arrays of objects by writing comparator functions that access and compare specific properties—use subtraction for numbers and comparison operators for strings.