Sort array of objects by string property value
To sort an array of objects by a string property, use array.sort((a, b) => a.prop.localeCompare(b.prop))
. Here's an example:
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:
The art of reverse sorting
To sort in descending order, flip a
and b
:
An operator that switch sorting properties at will
Unleash the power of a dynamicSort function to sort by any property:
For times when one property just isn't enough
Your multi-property sorting solution: A function to sort by multiple criteria:
Sorting without changing original array
To sort an array without altering the original, make use of Array.from()
:
Leveraging libraries for sorting
If you're into external libraries, both Underscore.js or Lodash have a sortBy
function:
Making sorting locale friendly
In a global readership, catering to internationalization is a must:
To handle neck-and-neck situations
To deal with identical values, resort to stable sort tactics to maintain original order:
Compatibility with older JavaScript versions
If you're dealing with legacy JS environments, use this:
Custom ordered sorting
For custom priority sorting, not alphabetically:
Was this article helpful?