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

In JavaScript, to sort an array of objects in descending 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 descending 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) => b.age - a.age);

console.log(employees);

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

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

Similarly, you can define comparison function for sorting an array of objects in descending 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 (b.name < a.name) {
    return -1;
  }

  if (b.name > a.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: "Wayne", age: 36 },
  { name: "John", age: 29 },
  { name: "David", age: 44 },
  { name: "Bruce", age: 21 },
] */

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


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.