Explain Codes LogoExplain Codes Logo

Sorting an array of objects by property values

javascript
custom-sorting
array-sort
javascript-arrays
Nikita BarsukovbyNikita Barsukov·Sep 21, 2024
TLDR

Sort an array of objects by key using Array.prototype.sort() in combination with a comparator function:

let inventory = [{ name: "Apple", price: "1.20" }, { name: "Pear", price: "0.80" }]; // Ascending order by 'price' inventory.sort((a, b) => parseFloat(a.price) - parseFloat(b.price)); // Call the sorting hotline for descending order by 'price' inventory.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));

Always remember to convert strings to numbers with parseFloat() or parseInt(), 'cause JavaScript can be weird sometimes. Trust me, I learnt the hard way. ES6 arrow functions are your friends, they're here to make your life easier.

Customized sorting

Sometimes, you need a tailor-made suit. Here's how custom sorting logic comes into play, like case-insensitive string comparison:

inventory.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));

Here, localeCompare helps you in dealing with sorting text with international alphabet support. Go global, my friend!

Pre-sorting steps and advice

Remember, Array.sort() is that naughty kid who keeps modifying the original array. To preserve original order, clone the array first:

let sortedInventory = [...inventory].sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

And since we're friends now, I'll let you in on a secret. For better performance, use let or const, but if you're partying in the Old JavaScript Town, make sure you've got your arrow function polyfill.

Sharability with helper functions

You don't want to write the same logic every time you need to sort, right? So create helper functions for each sorting operation. It's like preparing your lunchbox before going to work:

const byPrice = (a, b) => parseFloat(a.price) - parseFloat(b.price); // Now, apply this function anywhere you want to sort by 'price' inventory.sort(byPrice);

Helper functions are like these little magic spells: they increase reusability, maintainability, and let your code take a beauty sleep.

Time for some expert tips

Thanks to our friendly orchestra, we've got a good sense of how to order properties, but how about multilevel sorting or handling dynamic property names? Check out utility libraries like Lodash for these sorting adventures.

Multilevel sorting

Want to create a harmonious symphony? You can sort by multiple properties—first by city, then by price:

inventory.sort((a, b) => { return a.city.localeCompare(b.city) || Number(a.price) - Number(b.price); });

The || operator ensures the band plays on even if the first comparison hits a wrong note (returns 0).