How to Sort Strings in JavaScript Using localeCompare
When attempting to sort a list of objects based on a string attribute using the traditional approach of list.sort(function (a, b) { return a.attr - b.attr }), you may encounter unexpected results. This is because the subtraction operator (-) does not inherently sort strings in JavaScript.
To effectively sort strings in this scenario, utilize the String.prototype.localeCompare method. This method compares two strings and returns a negative number if the first string is sorted before the second string, a positive number if the second string is sorted before the first string, or zero if both strings are equal.
Here's how you can adapt your code using localeCompare:
list.sort(function (a, b) { return ('' + a.attr).localeCompare(b.attr); });
By explicitly casting a.attr to a string, we avoid potential exceptions. localeCompare offers support since Internet Explorer 6 and Firefox 1.
The above is the detailed content of How to Properly Sort Strings in JavaScript using `localeCompare`?. For more information, please follow other related articles on the PHP Chinese website!