javascript sort array of objects by property 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: sort array of objects by string property value

function compareFirstNames( a, b ) {
  if ( a.first_name < b.first_name ){
    return -1;
  }
  if ( a.first_name > b.first_name ){
    return 1;
  }
  return 0;
}

var people =[
    {"first_name":"Carol", "age":29},
    {"first_name":"Anna", "age":32},
    {"first_name":"Bob", "age":32}
];

people.sort( compareFirstNames ); //people is now sorted by first name from a-z