sort str arrays js 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: javascript order by string array
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
Example 3: javascript sort object
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 28800
};
var sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
Example 4: array sort js
arr = ['width', 'score', done', 'neither' ]
arr.sort()
arr.sort((a,b) => a.localeCompare(b))
arr = [21, 7, 5.6, 102, 79]
arr.sort((a, b) => a - b)