xxxxxxxxxx
const str = 'sorting'; //sorting a string
str.split('').sort().join(''); //output: ginorst
xxxxxxxxxx
function alphabeticalOrder(arr) {
return arr.sort((a, b) => a < b ? -1 : 1)
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
// [ 'a', 'a', 'c', 'd', 'g', 'z' ]
xxxxxxxxxx
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é']
xxxxxxxxxx
// Alphabetically
const ascending = data.sort((a, b) => a[field].localeCompare(b[field]))
// Descending
const descending = ascending.reverse()
xxxxxxxxxx
let users = [{
firstName: "Ahmed",
lastName: "ElNawawy",
},
{
firstName: "Khaled",
lastName: "ElNawawy",
}
];
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
xxxxxxxxxx
var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) =>
a.localeCompare(b)//using String.prototype.localCompare()
);
xxxxxxxxxx
//sort array alphabetically
objArray.sort(function(a, b) {
return a.localeCompare(b);
});
xxxxxxxxxx
*************sort String*************
1. arr.sort(function(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
});
**************************************************************
2. users.sort((a, b) => a.firstname.localeCompare(b.firstname)) // Anuj Kashyap
xxxxxxxxxx
// Alphabetically
const ascending = data.sort((a, b) => a[field].localeCompare(b[field]))
// Descending
const descending = ascending.reverse()
xxxxxxxxxx
users.sort((a, b) => a.firstname !== b.firstname ? a.firstname < b.firstname ? -1 : 1 : 0);