javascript sort array of objects by key value alphabetically code example

Example 1: sort object alphabetically javascript

//Sort object by v1 property alphabetically (case insensitive)
let objArray= [
  {v1:"Bee", v2: 2}, 
  {v1:"Apple", v2: 8}, 
  {v1:"bat", v2: 4},
];
let sortedArray= objArray.sort(function(a, b) {
   return a.v1.localeCompare(b.v1);
}); // [{v1: "Apple", v2: 8}, {v1: "bat", v2: 2}, {v1: "Bee", v2: 2}]

Example 2: 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 3: js order alphabetically

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