Home > Article > Web Front-end > How to Correctly Sort Strings in JavaScript?
Sorting Strings in JavaScript
Many JavaScript developers encounter challenges when attempting to sort a list of objects based on a string attribute due to the unique behaviors of strings in JavaScript. This article explores the solutions to this common issue.
Problem:
As you discovered, simply subtracting one string from another, as in a.attr - b.attr, does not accurately sort strings in JavaScript. This is because JavaScript treats strings as Unicode characters, and basic arithmetic operations are not suitable for comparing them.
Solution:
To sort strings effectively, you can utilize the String.prototype.localeCompare method. This method provides a locale-sensitive comparison of strings, making it more suitable for sorting. Here's an updated version of your code using localeCompare:
list.sort(function(a, b) { return ('' + a.attr).localeCompare(b.attr); });
Note that we have added an empty string concatenation ('' a.attr) to ensure that both values are coerced into strings. This is to avoid potential exceptions.
Alternatives:
If you prefer a more succinct approach and don't need to consider locale-sensitivity, you can use the following code snippet:
if (item1.attr < item2.attr) return -1; if ( item1.attr > item2.attr) return 1; return 0;
The above is the detailed content of How to Correctly Sort Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!