In the previous article, we explored how to sort an object's properties by their values in JavaScript. Now let's discover how to sort an array of objects by a specific property value in JavaScript.

Let's consider an array of users with their names and ages:

const users = [
  { name: 'John Deo', age: 23 },
  { name: 'Mike Datson', age: 21 },
  { name: 'Alex Kate', age: 45 }
]

We can sort these users based on either their name or age using the sort() method provided by JavaScript arrays.

The sort() method also accepts a callback function, which allows us to implement a custom comparator. This callback function takes two parameters representing the elements of the array to be compared at any given time:

const sorted = users.sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0))
console.log(sorted)

In the comparison, we return 1, 0, or -1 to indicate the result. If 1 is returned, it means a is considered greater than b. 0 indicates equality, and -1 signifies that b is considered lesser than a.

The resulting output will be:

[
  { name: 'Alex Kate', age: 45 },
  { name: 'John Deo', age: 23 },
  { name: 'Mike Datson', age: 21 }
]

Note: When comparing strings, uppercase and lowercase letters have different weights. For example, the lowercase letter a takes precedence over the uppercase letter A. Therefore, it is advisable to either convert strings to lowercase or uppercase before comparison.

To account for both lowercase and uppercase letters, let's update our callback function:

const sorted = users.sort((a, b) => (a.name.toLowerCase() > b.name.toLowerCase() ? 1 :
a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 0))

Similarly, we can also sort users based on their age. Since age is an integer, the callback function can be simplified as follows:

const sorted = users.sort((a, b) => a.age - b.age)
console.log(sorted)

After sorting by age, the sorted array will be:

[
  { name: 'Mike Datson', age: 21 },
  { name: 'John Deo', age: 23 },
  { name: 'Alex Kate', age: 45 }
]

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .