compare string js sort array code example
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: sort js array array
var ages = [18, 21, 9, 41, 35, 24]
ages.sort(function(a, b) {
return a - b
})
// => [9, 18, 21, 24, 35, 41]