Monday, February 19, 2018

How to sort strings in JavaScript



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?


Answer



Use String.prototype.localeCompare a per your example:



list.sort(function (a, b) {
return ('' + a.attr).localeCompare(b.attr);
})



We force a.attr to be a string to avoid exceptions. localeCompare has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale:



if (item1.attr < item2.attr)
return -1;
if ( item1.attr > item2.attr)
return 1;
return 0;


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...