How to Sort a JavaScript Array of Objects in Ascending Order by Key?

Sorting array of objects in ascending order by object key

In JavaScript, to sort an array of objects in ascending order based on a certain key/property, you can pass a comparison function as the argument to the Array.prototype.sort() method, using either of the following syntax:

sort((a, b) => { /* ... */ }) // ES6+
sort(function compareFn(a, b) { /* ... */ })

Where the compare function should return:

  • -1, to sort a before b;
  • 1, to sort a after b, or;
  • 0, to leave order of a and b remains unchanged.

In versions prior to ES10, elements that compare equal might not retain their original order, because in those version the Array.prototype.sort() method is not guaranteed to use stable sort algorithm.

Therefore, you can sort an array of objects in ascending order (based on numeric object values), like so:

// ES6+
const employees = [
  { name: 'John', age: 29 },
  { name: 'Wayne', age: 36 },
  { name: 'David', age: 44 },
  { name: 'Bruce', age: 21 },
];

employees.sort((a, b) => a.age - b.age);

console.log(employees);

This would sort the array of objects based on the comparison of numbers, producing the following result:

/* [
  { name: "Bruce", age: 21 },
  { name: "John", age: 29 },
  { name: "Wayne", age: 36 },
  { name: "David", age: 44 },
] */

Similarly, you can define comparison function for sorting an array of objects in ascending order (based on string object values), like so:

// ES6+
const employees = [
  { name: 'John', age: 29 },
  { name: 'Wayne', age: 36 },
  { name: 'David', age: 44 },
  { name: 'Bruce', age: 21 },
];

employees.sort((a, b) => {
  if (a.name < b.name) {
    return -1;
  }

  if (a.name > b.name) {
    return 1;
  }

  return 0;
});

console.log(employees);

This would sort the array of objects based on the comparison of strings, producing the following result:

/* [
  { name: "Bruce", age: 21 },
  { name: "David", age: 44 },
  { name: "John", age: 29 },
  { name: "Wayne", age: 36 },
] */

If you wish to compare locale-dependent strings, then you can use the String.prototype.localeCompare() method in the comparison function.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.