sort array alphabetical order javascript code example

Example 1: js order alphabetically

// Alphabetically
const ascending = data.sort((a, b) => a[field].localeCompare(b[field]))
// Descending
const descending = ascending.reverse()

Example 2: javascript string array sort alphabetically

var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) =>
   a.localeCompare(b)//using String.prototype.localCompare()
);

Example 3: string sort javascript

var names = ["Peter", "Emma", "Jack", "Mia"];
var sorted = names.sort(); // ["Emma", "Jack", "Mia", "Peter"]