Explain Codes LogoExplain Codes Logo

Sorting object property by values

javascript
sorting
comparator
data-types
Nikita BarsukovbyNikita Barsukov·Dec 18, 2024
TLDR

To swiftly sort an object by values in JavaScript, meld the power of Object.entries(), sort(), and Object.fromEntries():

const obj = { apple: 3, orange: 2, banana: 1 }; // Woah, watch out, things are about to get sorted in this function! const sortedObj = Object.fromEntries(Object.entries(obj).sort((a, b) => a[1] - b[1]));

This piece of magic transforms your obj into a sorted object, ascending by value. The simplicity of it!

Sorting considerations: Dodge the pitfalls

When you're sortin' to write home about, think about your data types. Are they all the same, or are you trying to compare apples and oranges? (Yes, that was a pun. You're welcome.)

Also, be case-insensitive. Your strings don't care if you're yelling at them. Use toLowerCase() or toUpperCase(). They don't discriminate. 😉

For dates, befriending Date objects to sort them out correctly will save you a headache. Oh, and remember: identical values can get a little clingy. Handle with care to maintain their order.

Lastly, that Object.fromEntries()? Mighty handy but tough on compatibility. It joined the gang in ES10 (a.k.a. ECMAScript 2019), so double-check your environment.

Sorting hacks for the serious folks

Advanced: Custom-sorting your complicated data

Flexibility is your friend with complex data. Craft a custom comparator function and you're golden:

// Use localeCompare for real, case-insensitive string values. Like an insensitive shrink. entries.sort((a, b) => a[1].toLowerCase().localeCompare(b[1].toLowerCase()));

Sorted safe? Going the immutable way

Use slice() before sorting to ensure your original does not mutate. It's like insuring your car before a road trip:

// Creating a GHOUL (Get Hands Off Un-altered List) const entriesCopy = entries.slice().sort(myComparator);

Efficient, pitfalls-free sorting? Yes, please!

Prepping your data can help you skip unnecessary calculations. Sort like a snake, avoid mutations at all costs.

Sorting with reduce: because we can

Reduce() and sort() are pals. Together, they can rebuild an object with ordered properties:

// Talk about a fantastic duo! const sortedObj = Object.entries(obj).sort(comparator) .reduce((acc, [key, val]) => ({ ...acc, [key]: val }), {});