sort string by alphabetical order javascript code example
Example 1: javascript sort alphabetically
var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort(function (a, b) {
return a.localeCompare(b); //using String.prototype.localCompare()
});
// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
Example 2: alphabetical order array javascript
arr.sort(function(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
});
Example 3: javascript sort array strings alphabetically
//sort array alphabetically
objArray.sort(function(a, b) {
return a.localeCompare(b);
});
Example 4: javascript alphabetical sort in order
function alphabetized(s) {
var ans="";
for (var i=97; i<123; ++i)
for (var j=0; j<s.length; j++)
if (s[j].toLowerCase().charCodeAt()==i)
ans+=s[j]
return ans
}
Example 5: put array in alphabetical order
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();