In this tutorial, you’ll learn how to sort array of objects in JavaScript. Depending on different scenarios you may be required to sort your JavaScript array objects by key or value or a date field.

Let’s start by creating an array of objects.

let arr = [
  {'name' : 'Roy'},
  {'name' : 'James'},
  {'name' : 'Andrew'}
];

For sorting an array you can utilize the Array.prototype.sort method. Here is how you can use it:

let arr = [
  {'name' : 'Roy'},
  {'name' : 'James'},
  {'name' : 'Andrew'}
];

let sorted = sortData(arr, 'desc');
console.log(sorted)

function sortData(data, order = 'asc'){
  if(order == 'asc'){
    return data.sort((a,b)=>{ 
      if(a.name < b.name) return -1; // a comes first
      if(a.name > b.name) return 1; // b comes first
      return 0;
    });
  } else {
    return data.sort((a,b)=>{ 
      if(a.name < b.name) return 1; // b comes first
      if(a.name > b.name) return -1; // a comes first
      return 0;
    });
  }
  return data;
}

As seen in the above code, you can pass a callback to the .sort method to decide how to sort. For ascending order you check if ASCII code of a is less than b and return -1 which means a comes first. If ASCII code of a is greater than b it returns 1 which means b comes first. Similarly for descending order.