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.