javascript sort() function code example
Example 1: javascript orderby
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
items.sort(function (a, b) {
return a.value - b.value;
});
items.sort(function(a, b) {
var nameA = a.name.toUpperCase();
var nameB = b.name.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
Example 2: sort a string in javascript
var string='ACBacb';
var sortedString = string.split('').sort().join('');
Example 3: 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 4: sort js array array
var ages = [18, 21, 9, 41, 35, 24]
ages.sort(function(a, b) {
return a - b
})