How to sort an array of objects by name property code example

Example 1: javascript sort array of objects

const books = [
  {id: 1, name: 'The Lord of the Rings'},
  {id: 2, name: 'A Tale of Two Cities'},
  {id: 3, name: 'Don Quixote'},
  {id: 4, name: 'The Hobbit'}
]

compareObjects(object1, object2, key) {
  const obj1 = object1[key].toUpperCase()
  const obj2 = object2[key].toUpperCase()

  if (obj1 < obj2) {
    return -1
  }
  if (obj1 > obj2) {
    return 1
  }
  return 0
}

books.sort((book1, book2) => {
  return compareObjects(book1, book2, 'name')
})

// Result:
// {id: 2, name: 'A Tale of Two Cities'}
// {id: 3, name: 'Don Quixote'}
// {id: 4, name: 'The Hobbit'}
// {id: 1, name: 'The Lord of the Rings'}

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

Example 3: javascript sort array of object by property

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

myDates.sort(sortByDate);//myDates is not sorted.