Explain Codes LogoExplain Codes Logo

Sort array of objects by string property value

javascript
sorting
case-insensitive
dynamic-sort
Nikita BarsukovbyNikita Barsukov·Aug 7, 2024
TLDR

To sort an array of objects by a string property, use array.sort((a, b) => a.prop.localeCompare(b.prop)). Here's an example:

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

This will sort the items array in alphabetical order based on the name property.

Comprehensive guide on sorting

Say no to case-sensitivity in sorting

For case-insensitive sorting, transform the string attributes to lower case:

items.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())); // All lowercase, because we don't do uppercase discrimination here!

The art of reverse sorting

To sort in descending order, flip a and b:

items.sort((a, b) => b.name.localeCompare(a.name)); // Because sometimes, Z to A feels just right!

An operator that switch sorting properties at will

Unleash the power of a dynamicSort function to sort by any property:

function dynamicSort(property) { return function (a, b) { return a[property].localeCompare(b[property]); // You say potato, I say po-tah-to, still the same sort function }; } items.sort(dynamicSort('name'));

For times when one property just isn't enough

Your multi-property sorting solution: A function to sort by multiple criteria:

function dynamicSortMultiple() { var props = arguments; return function (a, b) { for (var i = 0; i < props.length; i++) { var result = a[props[i]].localeCompare(b[props[i]]); if (result !== 0) return result; } return 0; // All things being equal, order maintains harmony }; } items.sort(dynamicSortMultiple('name', 'age')); // Name then age, because why not?

Sorting without changing original array

To sort an array without altering the original, make use of Array.from():

const sortedItems = Array.from(items).sort((a, b) => a.name.localeCompare(b.name)); // Sorted, cloned, no originals harmed!

Leveraging libraries for sorting

If you're into external libraries, both Underscore.js or Lodash have a sortBy function:

const sortedItems = _.sortBy(items, 'name'); // No one ever got fired for using a library!

Making sorting locale friendly

In a global readership, catering to internationalization is a must:

items.sort((a,b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' })); // Sort like the world's watching!

To handle neck-and-neck situations

To deal with identical values, resort to stable sort tactics to maintain original order:

items.sort((a, b) => { const nameComparison = a.name.localeCompare(b.name); return nameComparison !== 0 ? nameComparison : a.id - b.id; }); // In ties, the original triumphs!

Compatibility with older JavaScript versions

If you're dealing with legacy JS environments, use this:

items.sort(function(a, b) { return a.name.localeCompare(b.name); }); // Sort() function, the old but gold approach!

Custom ordered sorting

For custom priority sorting, not alphabetically:

const priority = ['History', 'Science Fiction', 'Fantasy', 'Mystery']; items.sort((a, b) => priority.indexOf(a.genre) - priority.indexOf(b.genre)); // Custom sorting: History before Mystery!