How to sort an array of objects by property values in JavaScript?
I have the following array of objects:
var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Beverly Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
How can I create a function to sort these objects by the price property in both ascending and descending order using only JavaScript?
To sort an array of objects by property values in JavaScript, you can use the built-in sort() method with a custom comparison function that compares the specific property values. For numeric properties like price, subtract the values to determine sort order: a.price - b.price for ascending and b.price - a.price for descending order.
Contents
- Basic Sorting with sort() Method
- Sorting by Numeric Property Values
- Creating a Reusable Sort Function
- Handling Different Data Types
- Avoiding Mutation of Original Array
- Advanced Sorting Techniques
- Practical Examples
Basic Sorting with sort() Method
The JavaScript sort() method is the primary tool for sorting arrays. By default, it sorts elements as strings in ascending order, but for sorting objects by their properties, you need to provide a custom comparison function.
var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Beverly Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
The comparison function takes two parameters (typically a and b) representing two elements from the array, and should return:
- A negative value if
ashould come beforeb - A positive value if
bshould come beforea - Zero if the order should remain unchanged
Sorting by Numeric Property Values
For numeric properties like price, you can use simple arithmetic to determine the sort order. This approach works well for numbers and numeric strings.
Ascending Order (Lowest to Highest)
homes.sort((a, b) => a.price - b.price);
Descending Order (Highest to Lowest)
homes.sort((a, b) => b.price - a.price);
Important: Since the
pricevalues in your example are strings, they should be converted to numbers for proper sorting:
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
Creating a Reusable Sort Function
For better code organization and reusability, you can create a generic sort function that can handle different properties and sort orders.
function sortByProperty(array, property, order = 'asc') {
return array.sort((a, b) => {
const valueA = parseFloat(a[property]);
const valueB = parseFloat(b[property]);
if (order === 'asc') {
return valueA - valueB;
} else {
return valueB - valueA;
}
});
}
// Usage examples:
sortByProperty(homes, 'price', 'asc'); // Ascending
sortByProperty(homes, 'price', 'desc'); // Descending
As SitePoint explains, this function has two parameters — the key we want to sort by and the order of the results (ascending or descending).
Handling Different Data Types
Different property types require different comparison approaches:
Numeric Properties
// Ascending
array.sort((a, b) => a.price - b.price);
// Descending
array.sort((a, b) => b.price - a.price);
String Properties
// Ascending (A-Z)
array.sort((a, b) => a.name.localeCompare(b.name));
// Descending (Z-A)
array.sort((a, b) => b.name.localeCompare(a.name));
Date Properties
// Ascending (oldest to newest)
array.sort((a, b) => new Date(a.date) - new Date(b.date));
// Descending (newest to oldest)
array.sort((a, b) => new Date(b.date) - new Date(a.date));
Avoiding Mutation of Original Array
The sort() method sorts arrays in place, which means it modifies the original array. To preserve the original array, create a copy first:
// Using spread operator (ES6+)
const sortedHomes = [...homes].sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
// Using slice()
const sortedHomes = homes.slice().sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
// Using Array.from()
const sortedHomes = Array.from(homes).sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
As 30 seconds of code demonstrates, creating a copy of the array using the spread operator avoids mutating the original array.
Advanced Sorting Techniques
Multiple Property Sorting
homes.sort((a, b) => {
const priceDiff = parseFloat(a.price) - parseFloat(b.price);
if (priceDiff !== 0) return priceDiff;
return a.city.localeCompare(b.city); // Sort by city if prices are equal
});
Case-Insensitive String Sorting
homes.sort((a, b) => a.city.toLowerCase().localeCompare(b.city.toLowerCase()));
Custom Sorting Logic
homes.sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
// Sort by price range
if (priceA < 200000 && priceB >= 200000) return -1;
if (priceA >= 200000 && priceB < 200000) return 1;
return priceA - priceB;
});
Practical Examples
Here are complete examples using your specific data structure:
Example 1: Basic Price Sorting
var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Beverly Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
// Ascending order by price
const ascendingPrice = [...homes].sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
console.log(ascendingPrice);
/*
Output:
[
{h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500"},
{h_id: "4", city: "Beverly Hills", state: "CA", zip: "90210", price: "319250"},
{h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500"}
]
*/
// Descending order by price
const descendingPrice = [...homes].sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
console.log(descendingPrice);
/*
Output:
[
{h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500"},
{h_id: "4", city: "Beverly Hills", state: "CA", zip: "90210", price: "319250"},
{h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500"}
]
*/
Example 2: Advanced Sorting Function
function sortHomes(homes, sortBy, order = 'asc') {
const sorted = [...homes]; // Create copy to avoid mutation
sorted.sort((a, b) => {
let valueA, valueB;
// Handle different data types
if (typeof a[sortBy] === 'string' && !isNaN(a[sortBy])) {
// Numeric string
valueA = parseFloat(a[sortBy]);
valueB = parseFloat(b[sortBy]);
} else if (typeof a[sortBy] === 'number') {
// Number
valueA = a[sortBy];
valueB = b[sortBy];
} else {
// String or other
valueA = a[sortBy].toString().toLowerCase();
valueB = b[sortBy].toString().toLowerCase();
}
// Apply sort order
if (order === 'asc') {
if (typeof valueA === 'number') {
return valueA - valueB;
}
return valueA.localeCompare(valueB);
} else {
if (typeof valueA === 'number') {
return valueB - valueA;
}
return valueB.localeCompare(valueA);
}
});
return sorted;
}
// Usage examples:
console.log(sortHomes(homes, 'price', 'asc'));
console.log(sortHomes(homes, 'price', 'desc'));
console.log(sortHomes(homes, 'city', 'asc'));
Sources
- Array.prototype.sort() - JavaScript | MDN
- JavaScript Array Sort - W3Schools
- Sort an Array of Objects in JavaScript with the sort() method— SitePoint
- How to Sort an Array of Objects by Property Values in JavaScript
- Sort an Array of Objects in JavaScript - 30 seconds of code
- How to sort an array of objects by string property value in JavaScript · CoreUI
- JavaScript: Sort an array of objects by a numeric property in each object - Stack Overflow
Conclusion
Sorting arrays of objects by property values in JavaScript is straightforward once you understand the sort() method and comparison functions. Key takeaways include:
- Use
a.price - b.pricefor ascending numeric sorting andb.price - a.pricefor descending order - Convert string numbers to actual numbers with
parseFloat()for accurate numeric sorting - Create copies of arrays using spread operator (
[...array]) orslice()to avoid mutating original data - Build reusable functions that can handle different properties and sort orders
- Use
localeCompare()for string comparisons and handle different data types appropriately - Consider edge cases like missing properties or mixed data types in your sorting logic
By implementing these techniques, you can efficiently sort your array of home objects by price or any other property in either ascending or descending order while maintaining clean, maintainable code.