How to Sort Array of Objects in JavaScript Easily
To sort an array of objects in JavaScript, use the
sort() method with a compare function that compares object properties. The compare function takes two objects and returns a number to determine their order.Syntax
The sort() method sorts the elements of an array in place. When sorting objects, you provide a compare function that tells JavaScript how to order the objects based on their properties.
array.sort((a, b) => a.property - b.property): Sorts numerically by a property.array.sort((a, b) => a.property.localeCompare(b.property)): Sorts strings alphabetically by a property.
javascript
array.sort((a, b) => {
if (a.property < b.property) return -1;
if (a.property > b.property) return 1;
return 0;
});Example
This example shows how to sort an array of objects by a numeric property age and a string property name.
javascript
const people = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 20 }, { name: 'Charlie', age: 30 } ]; // Sort by age ascending people.sort((a, b) => a.age - b.age); console.log('Sorted by age:', people); // Sort by name alphabetically people.sort((a, b) => a.name.localeCompare(b.name)); console.log('Sorted by name:', people);
Output
Sorted by age: [ { name: 'Bob', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 } ]
Sorted by name: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 20 }, { name: 'Charlie', age: 30 } ]
Common Pitfalls
One common mistake is forgetting that sort() changes the original array. Another is not returning the correct values in the compare function, which should be negative, zero, or positive.
Also, sorting strings without localeCompare() can lead to incorrect alphabetical order.
javascript
const items = [ { value: 'banana' }, { value: 'apple' }, { value: 'cherry' } ]; // Wrong: returns boolean, not number // items.sort((a, b) => a.value > b.value ? 1 : -1); // Right: use localeCompare for strings items.sort((a, b) => a.value.localeCompare(b.value)); console.log(items);
Output
[ { value: 'apple' }, { value: 'banana' }, { value: 'cherry' } ]
Quick Reference
- Numeric sort:
array.sort((a, b) => a.num - b.num) - String sort:
array.sort((a, b) => a.str.localeCompare(b.str)) - Descending order: reverse the subtraction or swap
aandb - Original array:
sort()changes it directly
Key Takeaways
Use the sort() method with a compare function to sort objects by their properties.
For numbers, subtract properties; for strings, use localeCompare for correct alphabetical order.
The sort() method modifies the original array, so copy it first if you want to keep the original.
Always return a negative, zero, or positive number in the compare function to define order.
Be careful not to return booleans in the compare function, as it leads to incorrect sorting.