How to use JavaScript to sort an array of objects by a specific key like price?

I have an array of objects retrieved via AJAX:

var homes = [
    { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" },
    { "h_id": "4", "city": "Bevery Hills", "state": "CA", "zip": "90210", "price": "319250" },
    { "h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" }
];

How can I write a function to JavaScript sort array of objects by key, specifically the price property, in either ascending or descending order?

I’ve done this countless times while working on UI components that show listings or product cards. If you’re just getting started and want a quick way to sort by price (lowest to highest), here’s a simple one-liner using parseFloat to safely handle string numbers:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
console.log(homes);

This is a straightforward example of using javascript sort array of objects by key when your key is price. The key detail is using parseFloat() so you don’t accidentally sort as strings (which happens if your prices come in as "100" instead of 100).

Yep, totally agree with @emma-crepeau —I use that all the time. Now, if you’re working on a UI that lets users toggle sort order (like switching between “cheapest” and “most expensive”), you can flip the comparison easily:

homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
console.log(homes);

This is basically the same logic but reversed. Still a clean way to implement javascript sort array of objects by key, but now for descending order. I usually keep both variants handy when building table columns that support sort toggles.

Love both of these takes. In fact, I ran into this a lot while working on dynamic data tables in dashboards. So if you want more flexibility—like sorting by price, zipCode, or any other field—you can wrap this into a reusable function:

function sortByKey(array, key, direction = 'asc') {
  return array.sort((a, b) => {
    const valA = parseFloat(a[key]);
    const valB = parseFloat(b[key]);
    return direction === 'asc' ? valA - valB : valB - valA;
  });
}

Now you’ve got a plug-and-play way to javascript sort array of objects by key—any key, any direction. I usually pair this with dropdown filters or sortable column headers to make sorting super dynamic and user-friendly.