I have a list of objects I wish to sort based on a field attr of type string. I tried using -
list.sort(function (a, b) { return a.attr - b.attr })
but found that - doesn’t appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string?
Use
String.prototype.localeCompareas per your example:We force a.attr to be a string to avoid exceptions.
localeComparehas been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn’t respect a locale: