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: array sort by alphabetical javascript
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
Example 3: javascript order by string array
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
Example 4: sort a string in javascript
var string='ACBacb';
var sortedString = string.split('').sort().join('');
Example 5: arr.sort
//sort an array of strings
var fruitSalad = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
//sort an array of numbers
var scores = [1, 10, 2, 21];
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
//sorts an array of words
var randomThings = ['word', 'Word', '1 Word', '2 Words'];
randomThings.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.
Example 6: sort function explained javascript
var sortedArray = myArray.sort(function(a,b){
if (a.name < b.name)
return -1;
else if (a.name == b.name)
return 0;
else
return 1;
});