sort string js code example
Example 1: alphabetical order array javascript
arr.sort(function(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
});
Example 2: javascript order by string array
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
Example 3: js order string
function reorderStr(str) {
return [...str].sort().join('');
}
console.log(reorderStr("hacker"));
console.log(reorderStr("javascript"));
Example 4: sort a string in javascript
var string='ACBacb';
var sortedString = string.split('').sort().join('');
Example 5: javascript sort
var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort();
var objs = [
{name: "Peter", age: 35},
{name: "Emma", age: 21},
{name: "Jack", age: 53}
];
objs.sort(function(a, b) {
return a.age - b.age;
});
Example 6: sort arrays according to first array js
itemsArray.sort(function(a, b){
return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});